ImportError
ImportError: cannot import name 'X' from partially initialized module 'Y' (most likely due to a circular import)
Traceback
Traceback (most recent call last):
File "main.py", line 5, in <module>
from a import helper_a # circular!
ImportError: cannot import name 'X' from partially initialized module 'Y' (most likely due to a circular import)What causes this error
Two or more modules import from each other, creating a dependency cycle. Module A imports from B while B imports from A, and neither can finish loading.
How to fix it
Restructure code to eliminate the cycle — move shared code to a third module. Use late imports inside functions. Use `import module` instead of `from module import name`. Follow a layered architecture with clear dependency direction.
Code that causes this error
# a.py from b import helper_b # b.py from a import helper_a # circular!
Fixed code
# a.py
def get_helper_b():
from b import helper_b # late import
return helper_b
# Or restructure into a third module:
# common.py — shared code
# a.py — imports from common
# b.py — imports from commonAbout ImportError
This error occurs when two or more modules import from each other, creating a dependency cycle. When module A imports module B and module B imports module A, Python gets stuck because neither module can finish loading before the other. The error message (improved in Python 3.12) explicitly mentions 'circular import', making it easy to identify.
Circular imports are common in large projects where model, view, and utility modules reference each other. The fixes are: restructure code to break the cycle (move shared code to a third module), use late imports inside functions instead of at module level, or use `import module` instead of `from module import name` (since the full module import can handle partial initialization). Good project architecture with clear dependency layers prevents circular imports.
Common scenarios
Installing packages in a different virtual environment than the one in use
Circular imports between modules that depend on each other
Typos in module or package names in import statements
Naming a local file the same as a standard library module