Avoiding
Circular Imports
Learn why Python modules can get stuck in an infinite loop of importing each other, and master the strategies to break the cycle.
What Is a Python Import?
When you write import module_b inside a file, Python executes that file top-to-bottom and makes its names available. This is how code in one file can use functions, classes, or variables defined in another.
What Is a Circular Import?
A circular import happens when Module A imports Module B, and Module B imports Module A: either directly or through a chain of other modules. Python gets caught in a loop trying to finish loading both files at the same time.
Why Does It Matter?
How Python Loads a Module
The Core Rule
Walkthrough: A Cycle in Action
import vs from ... import
| import module_b | from module_b import func | |
|---|---|---|
| When name is resolved | At use time (module_b.func) | At import time |
| Circular import risk | Lower: name looked up later | Higher: name must exist now |
| Readability | Origin is always explicit | Shorter call syntax |
| Recommended in cycles? | ✓ Safer choice | ✕ Avoid at top level |
Five Strategies to Break the Cycle
Strategy 1: Restructure Modules
Strategy 2: Lazy Import
Instead of importing at the top of the file, move the import inside the function that needs it. The import only runs when the function is called: by then, both modules are fully loaded.
Strategy 4: TYPE_CHECKING Guard
When you only need another module for type hints (not runtime logic), wrap the import in a special block that never runs at runtime.
Example 1: The Broken Version
Example 1: The Fixed Version
Example 2: Three-Module Chain
Common Mistakes
Strategy Summary
| Strategy | Pros | Cons | Best For |
|---|---|---|---|
| Restructure modules | Cleanest fix, prevents future cycles | Requires refactoring | Long-term projects |
| Lazy import | Quick, minimal code change | Hidden dependencies | Quick fixes, prototypes |
| import module | Simple syntax change | Doesn't fix all cases | Mild cycles |
| TYPE_CHECKING | Zero runtime cost | Only for type hints | Typed codebases |
| Merge modules | Eliminates the cycle entirely | Larger files | Tightly coupled code |
Question 1 of 5
What is the root cause of a circular import error in Python?
Question 2 of 5
module_a.py:
from module_b import helper
def greet():
return helper("Hi")
module_b.py:
from module_a import greet
def helper(msg):
return msg + "!"
Which change would fix the circular import in this code?
Question 3 of 5
What does if TYPE_CHECKING: accomplish?
Question 4 of 5
Your module dependency graph must form a DAG. What does "DAG" stand for?
Question 5 of 5
Which of the following is the best long-term strategy for fixing a circular import?