I. What Is a Circular Import
A circular import refers to a circular dependency between two or more modules, causing them to import each other during initialization.
The simplest case is two modules importing each other.
For example, the project contains two files:
project/
├── main.py
├── module_a.py
└── module_b.py
module_a.py:
import module_b
def func_a():
return "Function A"
module_b.py:
import module_a
def func_b():
return "Function B"
The two modules import each other, forming a dependency relationship:
flowchart LR
A["module_a"] --> B["module_b"]
B --> A
style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style B fill:#F3EDFC,stroke:#C4B2E3,color:#334155
linkStyle default stroke:#A3B8AC,stroke-width:1.5px
This structure forms a circular dependency.
However, a circular import does not necessarily raise an error immediately.
If two modules only import each other and do not access names that have not yet been defined during module initialization, the import can sometimes still complete successfully.
The real problem tends to occur when one module accesses an attribute or function that the other module has not yet created, before that other module has finished initializing.
II. Why Circular Imports Occur in Python
To understand circular imports, you first need to understand Python's module import mechanism.
When executing:
import module_a
Python does not just read a file; it also has to perform module lookup, module object creation, module initialization, and cache management.
1. The Basic Module Import Process
When Python imports a module, it roughly goes through the following process:
- Check whether the target module already exists in
sys.modules. - If the module has not been loaded yet, invoke the import lookup mechanism.
- The finder locates the module and generates a module spec.
- The loader creates the module object.
- The module object is usually inserted into
sys.modulesfirst. - Execute the module's top-level code.
- Module initialization completes, and the import process ends.
The most critical point is: The module is usually inserted into sys.modules before its own top-level code is executed.
This is done to support recursive imports and prevent a module from being repeatedly created indefinitely during the import process.
But it also means that other modules may access a module object that has already been created but has not yet finished initializing.
2. The Module Initialization Process
flowchart TD
A["Execute import module_a"] --> B["Check sys.modules"]
B --> C{"Does the module already exist?"}
C -->|Yes| D["Return the cached module object"]
C -->|No| E["Find the module and create a ModuleSpec"]
E --> F["Create the module object"]
F --> G["Write to sys.modules"]
G --> H["Execute the module's top-level code"]
H --> I{"Did initialization succeed?"}
I -->|Yes| J["Module initialization complete"]
I -->|No| K["Clean up the failed module cache entry and raise an exception"]
style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style B fill:#F3EDFC,stroke:#C4B2E3,color:#334155
style C fill:#FFF5DE,stroke:#E8D29A,color:#334155
style D fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style E fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style F fill:#E8EDF2,stroke:#B8C3CE,color:#334155
style G fill:#F3EDFC,stroke:#C4B2E3,color:#334155
style H fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style I fill:#FFF5DE,stroke:#E8D29A,color:#334155
style J fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style K fill:#FBE9E9,stroke:#D9AAAA,color:#334155
linkStyle default stroke:#A3B8AC,stroke-width:1.5px
There is an important boundary condition for cache cleanup here: when a module itself fails during execution, the import system usually removes the cache entry for the target module that failed during this import, but other modules that were successfully imported and their side effects are not necessarily rolled back.
3. Why Write to sys.modules First
Suppose module A imports module B, and module B in turn imports module A.
If Python did not record module A in advance, then when module B imports A, it might create A again, leading to repeated imports over and over.
Placing the module object into sys.modules ahead of time allows recursive imports to find the already-created module object.
But at this point, module A may have executed only part of its code.
For example:
# module_a.py
print("A: starting initialization")
import module_b
def func_a():
return "A"
print("A: initialization complete")
# module_b.py
print("B: starting initialization")
import module_a
def func_b():
return "B"
print("B: initialization complete")
Run:
python -c "import module_a"
Possible output:
A: starting initialization
B: starting initialization
B: initialization complete
A: initialization complete
Although a circular import exists, neither module raises an error before accessing names the other has not yet defined.
This shows that a circular import and a circular import error are not exactly the same concept.
III. Typical Errors Caused by Circular Imports
The most common problem with circular imports is accessing an attribute of a module that has not finished initializing.
1. cannot import name
For example:
module_a.py:
from module_b import func_b
def func_a():
return "Function A"
module_b.py:
from module_a import func_a
def func_b():
return "Function B"
When Python starts importing from module_a:
- It begins executing
module_a.py. module_atries to importfunc_bfrommodule_b.- Python begins executing
module_b.py. module_btries to importfunc_afrommodule_a, which has not finished initializing.- At this point,
func_ahas not yet been defined. - The import fails.
Typical error message:
ImportError: cannot import name 'func_a' from partially initialized module 'module_a'
Here:
partially initialized module means the module has already been created and has entered the initialization process, but has not yet finished executing its top-level code.
2. AttributeError
Another case is importing the module itself and then accessing its attributes.
module_a.py:
import module_b
def func_a():
return "Function A"
result = module_b.func_b()
module_b.py:
import module_a
def func_b():
return module_a.func_a()
When module_a has not yet defined func_a, module_b calling it may trigger:
AttributeError: partially initialized module 'module_a' has no attribute 'func_a'
This kind of error is usually related to module initialization order.
3. The difference between the two errors
| Error type | Common cause |
|---|---|
ImportError |
Using from module import name when the target name has not yet been created |
AttributeError |
The module has been imported, but an attribute that has not yet been created is accessed |
ModuleNotFoundError |
The module itself cannot be found by the import system; this is usually not a direct symptom of a circular import |
Note that circular imports can also raise other exceptions, so you cannot judge whether a circular dependency exists based on the exception name alone.
IV. Common Types of Circular Imports
1. Two modules directly importing each other
This is the simplest and most easily recognizable form.
module_a.py
imports module_b
module_b.py
imports module_a
Dependency relationship:
flowchart LR
A["module_a"] --> B["module_b"]
B --> A
style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style B fill:#F3EDFC,stroke:#C4B2E3,color:#334155
linkStyle default stroke:#A3B8AC,stroke-width:1.5px
2. Indirect circular imports among multiple modules
Circular dependencies do not necessarily occur between just two modules; they may also involve multiple modules.
For example:
module_a.py
imports module_b
module_b.py
imports module_c
module_c.py
imports module_a
Dependency relationships:
flowchart LR
A["module_a"] --> B["module_b"]
B --> C["module_c"]
C --> A
style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style B fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style C fill:#F3EDFC,stroke:#C4B2E3,color:#334155
linkStyle default stroke:#A3B8AC,stroke-width:1.5px
This situation is harder to troubleshoot than two modules directly importing each other, because when you look at an individual module in isolation, it may be difficult to see an obvious problem.
3. Circular imports inside a package
Circular imports also often occur inside Python packages.
For example:
project/
└── app/
├── __init__.py
├── user.py
├── order.py
└── common.py
user.py:
from app.order import Order
order.py:
from app.user import User
__init__.py:
from app.user import User
from app.order import Order
This structure may form multiple layers of indirect cycles.
In particular, when __init__.py centrally exports a large number of module members, importing one submodule may trigger the loading of other submodules, expanding the scope of the circular dependency.
4. Circular imports caused by type annotations
Sometimes business code does not directly call one another, but type annotations can create circular dependencies.
For example:
user.py:
from order import Order
class User:
def get_orders(self) -> list[Order]:
return []
order.py:
from user import User
class Order:
def get_user(self) -> User:
return User()
The two modules import each other in order to reference each other's types.
If these types are only used for static type checking and do not need to be resolved immediately at runtime, you can use TYPE_CHECKING and forward references.
V. Solution 1: Redesign module dependencies
This is the most recommended solution.
Circular imports often mean that module responsibilities are poorly separated or that dependency directions are unclear.
When solving the problem, you should prioritize adjusting the architecture rather than merely changing import statements.
1. Extract a shared module
Suppose:
user.py:
from order import Order
class User:
def create_order(self):
return Order()
order.py:
from user import User
class Order:
def __init__(self, user=None):
self.user = user
The two modules depend on each other.
If they share some basic definitions, you can extract the common definitions into a separate module.
For example:
project/
├── user.py
├── order.py
└── models.py
models.py:
class User:
def __init__(self, name):
self.name = name
class Order:
def __init__(self, order_id):
self.order_id = order_id
user.py:
order.py:
The dependencies are adjusted to:
```mermaid flowchart TD A["user.py"] --> C["models.py"] B["order.py"] --> C["models.py"] style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976 style B fill:#F3EDFC,stroke:#C4B2E3,color:#334155 style C fill:#E5F4EC,stroke:#A3CBB5,color:#334155 linkStyle default stroke:#A3B8AC,stroke-width:1.5px ```The two business modules no longer import each other directly; the shared definitions are provided by an independent module.
Note that extracting a shared module does not mean putting all code into a single common.py. Modules should be divided according to responsibility and stability, to avoid creating a new oversized dependency hub.
2. Introduce a service layer or coordination layer
When two business modules must collaborate, a higher-level coordination module can be added.
For example:
```text project/ ├── user.py ├── order.py └── services.py ```user.py:
order.py:
services.py:
The dependencies become:
```mermaid flowchart TD S["services.py"] --> U["user.py"] S --> O["order.py"] style S fill:#E0F0FE,stroke:#93BCE8,color:#1E4976 style U fill:#E5F4EC,stroke:#A3CBB5,color:#334155 style O fill:#F3EDFC,stroke:#C4B2E3,color:#334155 linkStyle default stroke:#A3B8AC,stroke-width:1.5px ```This approach suits scenarios where a business process needs to coordinate multiple modules.
The business modules handle their own core logic, while the coordination layer handles organizing the calls.
VI. Solution 2: Lazy Import
Lazy import means placing import statements inside functions or methods rather than at the top level of a module.
This postpones the establishment of module dependencies.
1. Put imports inside functions
For example:
module_a.py:
module_b.py:
Execution:
```python import module_a print(module_a.func_a()) ```When module_a is imported, module_b is not imported immediately.
Only when func_a() is executed does the corresponding import take place.
2. How lazy import works
flowchart TD
A["Import module_a"] --> B["Define func_a"]
B --> C["module_a initialization complete"]
C --> D["Call func_a"]
D --> E["Execute import inside function"]
E --> F["Load or get module_b"]
F --> G["Call func_b"]
G --> H["Return result"]
style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style B fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style C fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style D fill:#FFF5DE,stroke:#E8D29A,color:#334155
style E fill:#F3EDFC,stroke:#C4B2E3,color:#334155
style F fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style G fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style H fill:#E5F4EC,stroke:#A3CBB5,color:#334155
linkStyle default stroke:#A3B8AC,stroke-width:1.5px
Deferred imports can solve some circular import problems caused by initialization order.
However, they do not truly eliminate the dependencies between modules; they only change when the dependencies are established.
3. When to Use Deferred Imports
Suitable for:
- A module is used only in a specific function.
- Not all dependencies need to be loaded immediately during module initialization.
- Some dependencies are used only in specific feature branches.
- A third-party library has a high initialization cost.
- You need to avoid accessing other modules immediately at the top level of a module.
Not suitable for:
- The long-term dependency relationships themselves are poorly designed.
- Multiple modules call each other, forming complex business coupling.
- The dependencies still form an unmanageable cycle at runtime.
Deferred imports can serve as a solution, but they should not become a long-term way to cover up poor architecture.
VII. Solution 3: Using TYPE_CHECKING to Handle Type Annotations
Python's typing module provides the TYPE_CHECKING constant.
At normal runtime it is False, but static type checkers usually treat it as True, thereby analyzing the type imports inside it.
1. Direct Imports Cause Circular Dependencies
user.py:
from order import Order
class User:
def get_orders(self) -> list[Order]:
return []
order.py:
from user import User
class Order:
def get_user(self) -> User:
return User()
The two modules import each other only for type annotations.
2. Using TYPE_CHECKING
user.py:
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from order import Order
class User:
def get_orders(self) -> list["Order"]:
return []
order.py:
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from user import User
class Order:
def get_user(self) -> "User":
return User()
At normal runtime, the TYPE_CHECKING branch is not executed, so these type imports do not create runtime module dependencies.
3. The Execution Mechanism of TYPE_CHECKING
flowchart TD
A["Load module"] --> B["Check TYPE_CHECKING"]
B --> C{"Is it True?"}
C -->|Yes| D["Perform type import"]
C -->|No| E["Skip type import"]
D --> F["Used for static type checking"]
E --> G["Continue runtime logic"]
style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style B fill:#F3EDFC,stroke:#C4B2E3,color:#334155
style C fill:#FFF5DE,stroke:#E8D29A,color:#334155
style D fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style E fill:#E8EDF2,stroke:#B8C3CE,color:#334155
style F fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style G fill:#E5F4EC,stroke:#A3CBB5,color:#334155
linkStyle default stroke:#A3B8AC,stroke-width:1.5px
4. Forward References
A forward reference in a type annotation means using a string to represent a type name that has not yet been defined or does not need to be resolved for the time being.
For example:
def get_user() -> "User":
return User()
You can also use:
from __future__ import annotations
This enables deferred annotation evaluation behavior within the module, so that the type expressions in annotations do not have to be resolved immediately the way the traditional eager-evaluation approach does.
Note that starting with Python 3.14, the annotation evaluation mechanism has undergone an important change, adopting a deferred evaluation model by default. The behavior and future compatibility status of from __future__ import annotations across different versions must be judged in light of the target Python version.
Whether you use string forward references or deferred annotations, you cannot simply assume that they will automatically resolve all circular imports.
For example, if a function needs to use a certain type to construct an object at runtime, it may still need to actually import the corresponding module.
5. Caveats for TYPE_CHECKING
TYPE_CHECKING mainly solves dependency problems at the type-checking stage.
It is suitable for:
- Function parameter and return value types.
- Class attribute types.
- Generic type definitions.
- References between modules that are used only for type descriptions.
But if the referenced class needs to be used at runtime, for example:
obj = Order()
then you must ensure that the Order object can be obtained at runtime.
VIII. Solution 4: Use Dependency Injection
Dependency Injection (DI) is a design approach that reduces coupling between modules.
When two modules depend on each other, you can consider having an external party create the objects and then pass the dependencies in through constructor or method parameters.
1. Direct Dependencies Causing Circular Imports
For example:
user.py:
from order import OrderService
class UserService:
def __init__(self):
self.order_service = OrderService()
order.py:
from user import UserService
class OrderService:
def __init__(self):
self.user_service = UserService()
Here there is not only a circular import between modules, but also a risk of circular dependency in object creation.
Even if the module initialization error is resolved through deferred imports, objects may still end up being created endlessly.
2. Decoupling Through Dependency Injection
user.py:
class UserService:
def __init__(self, order_service=None):
self.order_service = order_service
order.py:
class OrderService:
def __init__(self, user_service=None):
self.user_service = user_service
main.py: