debugModeratepending
Python ImportError circular import -- module partially initialized
Viewed 0 times
circular importImportErrorpartially initializedTYPE_CHECKINGlazy import
python
Error Messages
Problem
Python raises ImportError: cannot import name X from partially initialized module Y. Two modules import from each other, creating a circular dependency.
Solution
Break the cycle: (1) Move shared code to a third module that both import. (2) Import inside the function instead of at module level (lazy import). (3) Restructure to remove the dependency cycle. (4) Use TYPE_CHECKING guard for type-only imports: from __future__ import annotations + if TYPE_CHECKING: import. (5) Use dependency injection instead of direct imports.
Why
Python executes module code top-to-bottom on first import. If module A imports B which imports A, A is only partially initialized when B tries to use it.
Revisions (0)
No revisions yet.