PLEASE READ BEFORE MARKING AS DUPLICATE
I have a a directory configured as such:
app.py
Modules/
__init__.py
a.py
b.py
Where _init_.py contains:
import a
import b
and a.py contains:
import b
Class A():
b_instance = b.B()`
and b.py contains:
import a
Class B():
a_instance = a.A()`
This entire /Modules
folder is imported from the main app.py.
It is my understanding that the execution will go as follows:
- app.py
import Modules
- /Modules/_init_.py
import a
- /Modules/a.py
import b
- /Modules/b.py
import a
(sees that a is already in sys.modules and continues) - /Modules/b.py executes Class B() and fails when trying to do:
a_instance = a.A()
because while a.py is in sys.modules, it has not yet executedclass A
and thus b.py cannot accessClass A
How then, can I have two classes which depend on each other and that dependency is linked at the highest scope of the class (i.e. not within a class method)?
The solutions given online assume that the class dependency occurs within some sub method which fixes the issue because the actual class is not needed until that specific function is executed. The difference of my issue is that the class dependency is directly in the Class, not within some method, so the actual class is needed immediately.