01 / 22

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.

Python

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.

import statement
Runs the target module and binds it to a name in the current namespace.
from ... import
Runs the target module, then copies specific names into the current namespace.

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.

module_a.py module_b.py import module_b import module_a

Why Does It Matter?

✕ Silent bugs
A name may exist but be None or incomplete, causing errors far from the actual problem.
✕ Hard to debug
The traceback points to the import line, not the architectural flaw that caused the cycle.
✕ Fragile code
Re-ordering imports or adding a new dependency can suddenly break a project that "used to work".

How Python Loads a Module

1
Check the cache: Python looks in sys.modules. If the module is already there, return it immediately.
2
Create a placeholder: A new, empty module object is placed in sys.modules before any code runs.
3
Execute top-to-bottom: Python runs every line in the file. Each def, class, and assignment adds names to the module object.
4
Return the module: Once execution finishes, the fully populated module is returned to the importer.

The Core Rule

✓ Acyclic (Good) main.py models.py utils.py config.py ✕ Cyclic (Bad) auth.py user.py perms.py

Walkthrough: A Cycle in Action

1 Python starts executing module_a.py 2 A hits import module_b: pauses, starts loading B 3 B hits import module_a: finds A in sys.modules 4 B receives A's half-finished placeholder 5 B tries to use a name from A that doesn't exist yet 6 AttributeError or ImportError

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

1
Restructure modules: move shared code into a third module that both can import.
2
Defer the import: move the import inside the function that needs it (lazy import).
3
Use import module instead of from module import name at the top level.
4
Use TYPE_CHECKING: guard type-hint-only imports behind if TYPE_CHECKING:
5
Merge modules: if two modules are deeply intertwined, they may belong in one file.

Strategy 1: Restructure Modules

Before (Cycle) auth user After (DAG) shared.py auth user → Extract shared definitions into a new module. Both original modules import from it: no cycle.

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.

module_a.py
# No top-level import of module_b def do_work(): import module_b # deferred: runs only when called return module_b.helper()

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.

module_a.py
from __future__ import annotations from typing import TYPE_CHECKING if TYPE_CHECKING: from module_b import MyClassB # only for type checkers def process(obj: MyClassB) -> None: # At runtime, MyClassB is never imported ...

Example 1: The Broken Version

orders.py
from customers import Customer class Order: def __init__(self, c): self.customer = c
customers.py
from orders import Order class Customer: def get_orders(self): return [Order(...)]

Example 1: The Fixed Version

orders.py
import customers # full module class Order: def __init__(self, c): self.customer = c
customers.py
import orders # full module class Customer: def get_orders(self): return [orders.Order(...)]

Example 2: Three-Module Chain

views.py services.py models.py from views import render_page Fix: lazy import in models.py

Common Mistakes

✕ Star imports everywhere
Using from module import * pulls in all names at import time, maximizing the chance of hitting an incomplete module.
✕ Ignoring the error
Wrapping the import in a try/except ImportError: pass hides the cycle instead of fixing it. The bug reappears unpredictably.
✕ God modules
Putting too much logic in one module that every other module imports: any addition can accidentally create a cycle.

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

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?