ImportError: cannot import name 'X' from partially initialized module 'Y' (most likely due to a circular import)
Educational use only. Content explains errors and defensive fixes for systems you own or are authorised to test. Do not use any technique here to access data, accounts, or networks without permission.
Root Cause
A circular import occurs in Python when module A imports module B, and module B simultaneously attempts to import module A. Because Python executes modules from top to bottom upon import, if A is only partially initialized when B tries to pull a function from it, Python throws this error. It points to a structural design flaw in the application where tightly coupled modules depend on each other for initialization.
Fix / Solution
The best solution is architectural: refactor the code to extract the shared functionality into a new, independent module (Module C) that both A and B can import without creating a loop. A quick, less elegant workaround is to move the `import` statement out of the global scope and place it inside the specific function or method where it is needed, deferring the import until runtime.
Code Snippet
# ❌ Circular Import (module_a.py and module_b.py)
# module_a.py: from module_b import func_b
# module_b.py: from module_a import func_a
# ✅ Fix 1: Deferred Import (Workaround)
def my_function():
from module_b import func_b
func_b()
# ✅ Fix 2: Refactor shared logic to module_c.py