How to avoid circular imports for dependent classes in python?

Viewed 928

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:

  1. app.py import Modules
  2. /Modules/_init_.py import a
  3. /Modules/a.py import b
  4. /Modules/b.py import a (sees that a is already in sys.modules and continues)
  5. /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 executed class A and thus b.py cannot access Class 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.

0 Answers
Related