Python import error

Imagine the following project structure

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

In a.py, I have a class A that uses class B from the b.py file and B from b.py uses A class a.py

if i write:

 from foo.b import B 

in a.py and

 from foo.a import A 

in b.py, recursion happens

How can I import correctly without combining A and B in one file

+4
source share
1 answer

Python does not support looping imports, in part because they are usually a symptom of erroneous design.

What you can do is make A and B standalone and link both of them to the third file, or, alternatively, extract the general structure into the third file and the link that will be obtained from both of your modules. How accurately this will work depends on what A and B and why you think they should know about each other.

For example, you can make A simply take a reference to an instance of B through your constructor, so you do not need to import:

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

This gets a little trickier if inheritance is involved. In this case, you probably do not want the superclass to know about the subclass, because this violates the principle of replacement.

+5
source

Source: https://habr.com/ru/post/1436006/


All Articles