atomAltera
atomAltera

Reputation: 1791

Import trouble in python

Imagine the following project structure

app/
    foo/
        __init__.py
        a.py
        b.py

In a.py i have class A which uses class B from b.py file, and B class from b.py uses A class form a.py

if I write:

from foo.b import B 

in a.py and

from foo.a import A

in b.py, the recursion occurs

How can I do properly import, without merging A and B in single file

Upvotes: 4

Views: 208

Answers (1)

Niklas B.
Niklas B.

Reputation: 95358

Python doesn't support circular imports, partly because they are usually a symptom of a flawed design.

What you can do is make A and B self-contained and reference both of them from a third file, or alternatively, extract the shared structure into a third fileand reference that from both your modules. How exactly this is going to work highly depends on what A and B are and why you think they should know of each other.

For example, you could make A just take a reference to an instance of B via its constructor, that way you won't need an import:

class A(object):
    def __init__(self, b):
        self.b = b
    # .. some methods that reference self.b

It gets a bit more complicated if inheritance is involved. In that case, you probably don't want the superclass to know of the subclass, because that would violate the substitution principle.

Upvotes: 5

Related Questions