Diagnose and Refactor Circular Imports
Core idea
A circular import happens when module A depends on B and B depends on A, directly or indirectly. Python can expose a module object before initialization finishes, so an imported name may not yet exist. A cycle does not always fail, but it can make initialization order fragile.
Reproduce a circular import failure
In a new empty directory, create the parent folders and these files (an empty file is marked by its filename alone):
bm_a.py
from bm_b import messagelabel = "A"bm_b.py
from bm_a import labelmessage = labelSave the following code as run.py and run python run.py from the new directory. Use a fresh directory for each example.
Expected error: ImportError. bm_a imports bm_b before defining label; bm_b tries to import that missing label from the partially initialized bm_a.
Extract shared definitions
In a new empty directory, create the parent folders and these files (an empty file is marked by its filename alone):
bm_common.py
label = "A"bm_b.py
from bm_common import labelmessage = label + "!"bm_a.py
from bm_b import messageSave the following code as run.py and run python run.py from the new directory. Use a fresh directory for each example.
Output: A!. bm_b depends on bm_common; bm_a depends on bm_b. The reverse dependency has been removed.
Defer a dependency until a call
In a new empty directory, create the parent folders and these files (an empty file is marked by its filename alone):
bm_a.py
label = "A"def describe(): from bm_b import message return messagebm_b.py
from bm_a import labelmessage = label + "!"Save the following code as run.py and run python run.py from the new directory. Use a fresh directory for each example.
Output: A!. describe is called after bm_a finishes initialization. The cycle still exists structurally; moving an import into a function is a tactical fix, not always the best architecture.
Common mistake
Reordering imports may hide a cycle rather than remove it. Prefer splitting shared definitions into a lower-level module or moving orchestration into a separate entry point; do not suppress ImportError indiscriminately.
Practice
Draw the dependency arrows for the failing example and the shared-module refactor. Verify that the refactored arrows contain no cycle.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Refactor dependency cycles
Check your understanding of circular imports.
A imports a name from B; B immediately imports a name from A that is defined later. What is the likely failure?
Which change removes a dependency cycle when both modules need one shared constant?
When can moving an import into a function help with an initialization cycle?
Does every circular dependency necessarily raise an error?