How to Fix Circular Import Error in Python
In this tutorial, you'll learn about How to Fix Circular Import Error in Python. We cover key concepts, practical examples, and best practices.
Python raises ImportError or produces AttributeError when two or more modules depend on each other directly or indirectly, creating a circular import loop.
The Wrong Way
# module_a.py
from module_b import func_b
def func_a():
return func_b()
# module_b.py
from module_a import func_a
def func_b():
return func_a()
Running python3 module_a.py produces:
ImportError: cannot import name 'func_b' from partially initialized module 'module_b' (most likely due to a circular import)
The Right Way
Move the import inside the function to break the cycle:
# module_a.py
def func_a():
from module_b import func_b
return func_b()
# module_b.py
from module_a import func_a
def func_b():
return func_a()
Step-by-Step Fix
1. Use lazy imports inside functions
# module_a.py
def get_b_func():
from module_b import func_b
return func_b()
2. Restructure into three modules
Create a shared module that both can import:
# shared.py
def shared_util():
pass
# module_a.py
from shared import shared_util
# module_b.py
from shared import shared_util
3. Import the module, not the name
# module_a.py
import module_b
def func_a():
return module_b.func_b()
# module_b.py
import module_a
def func_b():
return module_a.func_a()
4. Use init.py for deferred imports
# __init__.py
from .module_a import func_a
from .module_b import func_b
# This defers imports until they are actually accessed
Prevention Tips
- Design modules in a layered architecture without upward dependencies.
- Use dependency inversion -- let high-level modules depend on abstractions.
- Keep utility modules free of application-specific imports.
- Use lazy imports for optional dependencies only.
- Run
python3 -vto trace import order and detect cycles.
Common Mistakes with circular import
- Non-exhaustive pattern matches that compile with warnings then crash at runtime
- Misunderstanding that
Stringis[Char]with poor performance for large text operations - Using
foldlinstead offoldl'causing stack overflow on large lists
These mistakes appear frequently in real-world PYTHON code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.
Practice Exercise
Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.
This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.
FAQ
Built by the developers of Doda Browser, DodaZIP, and Durga Antivirus Pro.
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro