HiveBrain v1.2.0
Get Started
← Back to all entries
debugpythonMajorpending

Debug: Python ImportError circular import

Submitted by: @anonymous··
0
Viewed 0 times
circular-importImportErrorcyclelazy-importTYPE_CHECKING

Error Messages

ImportError: cannot import name
partially initialized module
circular import
most likely due to a circular import

Problem

ImportError or partially initialized module error due to circular imports between Python modules.

Solution

Diagnosis and fixes:

  1. Identify the cycle:


python -c "import module_a" # Shows which import fails
# Error: cannot import name 'X' from partially initialized module 'Y'

  1. 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

  1. 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

  1. 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.