0

I have the below directory structure:

src/
--check.py
--quantum/
----__init__.py
----ansatz.py
----hva/
------__init__.py
------single_layer_hva.py

In my check.py, I'm doing the below:

#check.py
import quantum.ansatz as a

a.get_ansatz('sample_ansatz')

In my ansatz.py, I'm doing the below:

#ansatz.py
import hva.single_layer_hva as hva

single_layer_hva = hva.SingleLayerHVA()

In my single_layer_hva, I'm have defined a class I want to use in ansatz.py:

class SingleLayerHVA

There is no issue while executing ansatz.py and the modules are getting imported properly.

But, I'm getting the below error while executing check.py:

Traceback (most recent call last):
  File "/workspaces/high-fidelity-quantum-state-preparation/src/check.py", line 1, in <module>
    import quantum.ansatz as a
  File "/workspaces/high-fidelity-quantum-state-preparation/src/quantum/ansatz.py", line 4, in <module>
    import hva.single_layer_hva as hva
ModuleNotFoundError: No module named 'hva'

I've tried following the steps mentioned in the below link, though it's not working. https://iq-inc.com/importerror-attempted-relative-import/

Can someone suggest what can be done regarding this issue?

Amey Meher
  • 101
  • 7
  • `from . hva import single_layer_hva as hva`? – MatBailie Feb 28 '23 at 03:45
  • check.py executes properly after making this change, though when I try to run ansatz.py, it gives me this error "ImportError: attempted relative import with no known parent package" – Amey Meher Feb 28 '23 at 03:47
  • Why do you Need a both to be executable? How are you executing them? `python3 -m src/quantum/ansatz.py` or something different? – MatBailie Feb 28 '23 at 03:53
  • I've got some tests within ansatz.py that I don't want to include in the check.py file. Executing both files through the run button on visual studio. – Amey Meher Feb 28 '23 at 03:56
  • 1
    Put the tests in a separate hierarchy, called `/tests` next to `/src` and use fully qualified (not relative) package references (`import quantum.hva.single_layer_hva as hva`) https://stackoverflow.com/questions/71773830/running-unittest-using-a-src-package-directory-structure – MatBailie Feb 28 '23 at 04:02
  • One thing I noticed is that when I make changes in ansatz.py after making the suggested change and then running my check.py is that the module with the changes is not reflected in the code. I have to restart the kernel each time after I make a change in ansatz.py to see the change getting reflected in check.py. – Amey Meher Feb 28 '23 at 04:21

0 Answers0