Amplify
Amplify

Reputation: 954

Python: Circular Import error, eventhough no "from ... import ..." used

I am struggeling with resolving a circular import issue. My setup is as follows:

Module a.py:

import b

class A():
    pass

Module b.py:

import a

class Bar(a.A):
    pass

Notice the circular import in module b: is needs to access class A from module a, because B inherits from A.

Finally, the main module, main.py:

import a

# ...

When I run main.py, I get this error:

$ python3 main.py
Traceback (most recent call last):
  File "/home/.../main.py", line 1, in <module>
    import a
  File "/home/.../a.py", line 1, in <module>
    import b
  File "/home/.../b.py", line 3, in <module>
    class Bar(a.A):
AttributeError: partially initialized module 'a' has no attribute 'A' (most likely due to a circular import)

I thought, one way of resolving circular imports was to not use the from ... import ... statement, which I didn't do as you can see. But why am I still getting that error then?

EDIT: My current code structure requires that A and B are separate modules. Nevertheless, in this video, he is using a similar structure as mine, and he has no problems...

Upvotes: 1

Views: 1777

Answers (1)

ti7
ti7

Reputation: 18792

The ideal answer in such cases is usually to

  • combine the files or their contents (do you actually need more files?)
  • create a 3rd file and put shared contents into it (avoids breaking existing imports as you can simply import whatever you need into the existing libraries from the shared one)
  • create a 3rd file which imports both (cleaner with 3rd party libraries, but may break existing logic)
import a
import b

class Bar(a.A):
    pass

Upvotes: 1

Related Questions