Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Circular import dependency in Python

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?

like image 222
Ram Rachum Avatar asked Oct 12 '09 19:10

Ram Rachum


People also ask

What is a circular dependency Python?

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.

How do you use circular import in Python?

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.

How can you prevent most likely due to circular imports?

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.


1 Answers

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.

like image 200
Dirk Avatar answered Sep 21 '22 21:09

Dirk