What is a circular import in Python, and how do you fix it?
A circular import happens when module A imports B while B imports A, so one of them is used before it is fully loaded, causing ImportError or AttributeError. Fix it by restructuring, moving the shared code to a third module, or importing inside the function.
Explain it simply
Two friends each say, "I will leave only after you leave." Neither ever leaves. In Python, A pauses halfway to load B, B asks for something A has not defined yet, and the import fails.
Example
# a.py
from b import b_value
a_value = 1
# b.py
from a import a_value
b_value = 2Running import a starts a.py, which asks for b, which in turn asks for a_value from a half-loaded a that has not reached its definition line. Result: ImportError: cannot import name 'a_value'.
Common fixes:
# 1. Move shared things into common.py that both import.
# 2. Import where it is used (lazy import):
def use_b():
from b import b_value
return b_value
# 3. Use "import b" and access b.b_value later, at call time.What to say in the interview
"A circular import is two modules depending on each other at import time. The best fix is design: move the shared code into a third module, or invert the dependency. Quick fixes are importing inside a function, or using import x instead of from x import y so the name is looked up later. For type hints only, use TYPE_CHECKING."