Fix Circular Imports in Python Modules
Why mutual top-level imports fail with ImportError or partially initialized module errors, and two clean ways to break the cycle.
By the end of this tutorial you will know:
- Why Python raises
ImportError: cannot import name ... from partially initialized module - How to break cycles cleanly by extracting shared types into a third module
- When a local (in-function) import or
TYPE_CHECKINGguard is appropriate
Prerequisites: Python 3 installed.
1. The big idea
When Python imports a.py, it executes a.py top to bottom. If a.py immediately does from b import func_b, Python pauses a.py and starts executing b.py. If b.py then does from a import func_a before a.py ever reached def func_a, a exists in memory—but func_a does not exist yet!
2. Reproducing the crash
from b import helper_b
def helper_a():
return "A"from a import helper_a
def helper_b():
return helper_a() + "B"Running python3 a.py fails with:
ImportError: cannot import name 'helper_a' from partially initialized module 'a' (most likely due to a circular import)3. The fix: extract shared code (or move the import)
Option A (Best): Extract shared pieces into shared.py
If a.py and b.py both need helper_a or shared models, put the shared code in a third module that imports neither a nor b.
def helper_a():
return "A"Option B: Move the import inside the function
If only one function needs helper_a (or you only need it for type hints), import it inside the function or under if TYPE_CHECKING::
def helper_b():
from a import helper_a
return helper_a() + "B"Run python3 -c "import b; print(b.helper_b())". It prints AB cleanly with zero ImportError.
4. Common pitfalls
| Mistake | Symptom | Fix |
|---|---|---|
| Putting models and routes in mutually importing files | cannot import name ... from partially initialized module | Move shared models/types into a models.py or types.py |
| Circular imports solely for type hints | Runtime ImportError | Gate type-only imports with if TYPE_CHECKING: |
5. What you learned
You now know why Python circular imports fail mid-initialization and how extracting a shared module, using TYPE_CHECKING, or scoping imports breaks the cycle.