debugpythonMajorpending
Debug: Python ImportError circular import
Viewed 0 times
circular-importImportErrorcyclelazy-importTYPE_CHECKING
Error Messages
Problem
ImportError or partially initialized module error due to circular imports between Python modules.
Solution
Diagnosis and fixes:
python -c "import module_a" # Shows which import fails
# Error: cannot import name 'X' from partially initialized module 'Y'
a) Import inside function (lazy import):
def my_function():
from module_b import SomeClass # Import when needed
return SomeClass()
b) Import the module, not the name:
import module_b # Instead of: from module_b import func
module_b.func() # Access at use time
a) Extract shared code to a third module:
# Instead of a.py <-> b.py
# Create common.py, import from both a and b
b) Use dependency injection:
class ServiceA:
def __init__(self, service_b): # Don't import B
self.b = service_b
c) Use TYPE_CHECKING for type hints only:
from __future__ import annotations
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from module_b import ClassB # Only for type checker
- Keep import graphs acyclic (DAG)
- Shared types/interfaces in a separate module
- Use linting: pylint --disable=all --enable=cyclic-import
- Identify the cycle:
python -c "import module_a" # Shows which import fails
# Error: cannot import name 'X' from partially initialized module 'Y'
- Quick fixes:
a) Import inside function (lazy import):
def my_function():
from module_b import SomeClass # Import when needed
return SomeClass()
b) Import the module, not the name:
import module_b # Instead of: from module_b import func
module_b.func() # Access at use time
- Proper fixes:
a) Extract shared code to a third module:
# Instead of a.py <-> b.py
# Create common.py, import from both a and b
b) Use dependency injection:
class ServiceA:
def __init__(self, service_b): # Don't import B
self.b = service_b
c) Use TYPE_CHECKING for type hints only:
from __future__ import annotations
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from module_b import ClassB # Only for type checker
- Prevention:
- Keep import graphs acyclic (DAG)
- Shared types/interfaces in a separate module
- Use linting: pylint --disable=all --enable=cyclic-import
Revisions (0)
No revisions yet.