Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Avoiding circular (cyclic) imports in Python?

One way is to use import x, without using "from" keyword. So then you refer to things with their namespace everywhere.

Is there any other way? like doing something like in C++ ifnotdef __b__ def __b__ type of thing?

like image 660
Dexter Avatar asked Dec 13 '12 20:12

Dexter


2 Answers

Merge any pair of modules that depend on each other into a single module. Then introduce extra modules to get the old names back.

E.g.,

# a.py
from b import B

class A: whatever

# b.py
from a import A

class B: whatever

becomes

# common.py
class A: whatever
class B: whatever

# a.py
from common import A

# b.py
from common import B
like image 99
Fred Foo Avatar answered Oct 01 '22 12:10

Fred Foo


Circular imports are a "code smell," and often (but not always) indicate that some refactoring would be appropriate. E.g., if A.x uses B.y and B.y uses A.z, then you might consider moving A.z into its own module.

If you do think you need circular imports, then I'd generally recommend importing the module and referring to objects with fully qualified names (i.e, import A and use A.x rather than from A import x).

like image 22
Edward Loper Avatar answered Oct 01 '22 12:10

Edward Loper