Let's say I have the following directory structure:
a\ __init__.py b\ __init__.py c\ __init__.py c_file.py d\ __init__.py d_file.py
In the a
package's __init__.py
, the c
package is imported. But c_file.py
imports a.b.d
.
The program fails, saying b
doesn't exist when c_file.py
tries to import a.b.d
. (And it really doesn't exist, because we were in the middle of importing it.)
How can this problem be remedied?
In python, a module can be made by importing other modules. In some cases, a Circular dependency is created. Circular dependency is the case when some modules depend on each other. It can create problems in the script such as tight coupling, and potential failure.
In simplest terms, a circular import occurs when module A tries to import and use an object from module B, while module B tries to import and use an object from module A. We'll run the code from run.py, which just imports a.py. As you can see, we get an exception as soon as b.py tries to import a.py.
You can, however, use the imported module inside functions and code blocks that don't get run on import. Generally, in most valid cases of circular dependencies, it's possible to refactor or reorganize the code to prevent these errors and move module references inside a code block.
You may defer the import, for example in a/__init__.py
:
def my_function(): from a.b.c import Blah return Blah()
that is, defer the import until it is really needed. However, I would also have a close look at my package definitions/uses, as a cyclic dependency like the one pointed out might indicate a design problem.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With