Sub topic 13
Circular imports and how to break them
This chapter assumes you know how sys.modules caches modules and that an import runs the module's code from top to bottom. It also assumes you can read a traceback and have used from x import y and import x. If those are new, read the chapters on import execution and import forms first.
What a circular import is
A circular import happens when module A imports module B while B, directly or through other modules, imports A. Python allows this. It fails only when one module in the loop reads a name from another module before that name exists.
The cause is the import order of events. When Python starts importing a module, it creates the module object and puts it in sys.modules before running the module's code. That prevents infinite loops, but it also means a second module can receive a half-built module whose later names are not defined yet.
A failing example
Two files, each importing a name from the other at the top level:
# orders.py
from customers import discount_for
def total(order):
return order["amount"] - discount_for(order["customer"])# customers.py
from orders import total
DISCOUNTS = {"ada": 5}
def discount_for(customer):
return DISCOUNTS.get(customer, 0)
def customer_total(customer, order_list):
return sum(total(o) for o in order_list if o["customer"] == customer)Run python -c "import orders" and you get this:
Traceback (most recent call last):
File "<string>", line 1, in <module>
File "orders.py", line 1, in <module>
from customers import discount_for
File "customers.py", line 1, in <module>
from orders import total
ImportError: cannot import name 'total' from partially initialized module 'orders' (most likely due to a circular import)The phrase "partially initialized module" is the signal. Python is telling you that orders is in sys.modules, but its code has not yet reached the def total line.
Notice that the failure depends on which module is imported first. If your entry point imports customers first, the loop runs the other way. Then customers is the partial module, and the error asks for discount_for instead. This is why circular imports often appear or vanish after an unrelated edit to import order.
Why `import x` often survives and `from x import y` does not
from orders import total needs the attribute total at the moment the statement runs. import orders only needs the module object, which already exists in sys.modules. The attribute lookup orders.total then happens later, when your function runs, by which time every module has finished loading.
# customers.py
import orders
DISCOUNTS = {"ada": 5}
def discount_for(customer):
return DISCOUNTS.get(customer, 0)
def customer_total(customer, order_list):
return sum(orders.total(o) for o in order_list if o["customer"] == customer)Here customers.py no longer reads total at load time. This works only as long as no code at module level uses orders.total. A call such as RESULT = orders.total(...) at the top level would fail again.
Four ways to break a cycle
Pick the fix by looking at why the two modules need each other.
| Fix | How | Best when | Cost |
|---|---|---|---|
| Extract shared code | Move the shared names into a third module that both import | Both modules need the same helper or constant | You change the layout |
| Import the module, not the name | Use `import x` and write `x.name` at call time | One direction only needs functions at call time | Slightly longer names |
| Deferred import | Put the import inside the function that needs it | One direction is rare or optional | Hidden dependency, small cost per call |
| Merge the modules | Combine them into one file | They are really one concept | Larger file |
Extract shared code
Cycles usually mean two modules share a responsibility that belongs in neither. Moving it out turns a cycle into a straight line, which is the most durable fix.
# pricing.py
DISCOUNTS = {"ada": 5}
def discount_for(customer):
return DISCOUNTS.get(customer, 0)# orders.py
from pricing import discount_for
def total(order):
return order["amount"] - discount_for(order["customer"])# customers.py
from orders import total
def customer_total(customer, order_list):
return sum(total(o) for o in order_list if o["customer"] == customer)Now the dependency arrows are customers -> orders -> pricing, with no way back.
Deferred import
When restructuring is too costly, move one import into the function. The module is then loaded at the first call, after both modules are fully built.
# orders.py
def total(order):
# Deferred import: customers.py imports orders at module level,
# so importing it here avoids a cycle at load time.
from customers import discount_for
return order["amount"] - discount_for(order["customer"])After the first call the module is in sys.modules, so later calls only pay for a dictionary lookup and a name binding. Treat deferred imports as a patch. Leave a comment that says why it is there, or a later cleanup will move it back to the top and reintroduce the error.
Cycles caused only by type hints
A common modern cause is two classes that mention each other in annotations. The annotations need the names only for type checkers, not at runtime. Guard the import with typing.TYPE_CHECKING, which is False at runtime:
# invoice.py
from __future__ import annotations
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from customer import Customer
class Invoice:
def __init__(self, owner: Customer, amount: int) -> None:
self.owner = owner
self.amount = amountThe from __future__ import annotations line stops Python from evaluating the annotation at definition time, so the missing runtime name causes no error. Tools such as mypy still see the import. One limit: code that reads annotations at runtime, such as typing.get_type_hints or some validation libraries, will fail to resolve Customer unless it is importable.
Cycles inside packages
Relative imports do not avoid cycles. from .circle import area in shapes/__init__.py and from . import something_from_init in circle.py can form the same loop. A frequent trap is a package's __init__.py that re-exports names from its submodules while those submodules import from the package itself. Prefer to import from the specific sibling module, such as from .util.mathx import square, rather than from the package root. The root's __init__.py is the module most likely to be half-built.
from package import submodule is slightly more forgiving than from package import name. If submodule is not yet an attribute of the package, Python falls back to looking it up in sys.modules. Do not build a design on this fallback.
A cycle that involves `__main__`
A script run directly is registered as __main__, not under its file name. If you run python orders.py and customers.py then does import orders, Python loads a second copy of the file under the name orders. You now have two module objects with separate globals. A class defined in the file exists twice, and isinstance checks between the copies fail. The fix is to keep entry-point scripts thin and import real code from modules, or to run packaged code with python -m package.module.
Diagnosing a cycle
- Read the traceback from the bottom. The last line names the partial module and the missing name.
- Follow the
Filelines upward. They show the chain of imports that led there, so you can see the loop. - Decide which module is the real dependency owner. The module that is lower level, with fewer responsibilities, should not import the higher one.
- Apply the lightest fix from the table, and prefer extraction when the loop reflects a design problem.
- Test with each module as the first import. Run
python -c "import orders"andpython -c "import customers", because a cycle can hide when only one order is tried.
Exercise
Two modules, a.py and b.py, each start with from b import g and from a import f respectively (f is defined in a.py after that import line, g in b.py after its import line). Running import a raises ImportError. Why does it fail, and what is the smallest change that fixes it without a third module?
Show answer
Importing a puts a in sys.modules and starts running a.py. Its first line imports b, which starts running b.py. b's first line asks for f from a, but a has not reached the def of f yet, so Python raises "cannot import name 'f' from partially initialized module 'a'". The smallest fix is a deferred import: remove the top-level import from one file and place it inside the function that uses it (for example, from a import f inside the function in b.py). Both modules then finish loading before the import runs. Changing b.py to import a and calling a.f(...) inside functions also works, provided nothing at module level uses a.f.