Sub topic 13
Circular imports and how to break them
This chapter assumes you know how import executes a module once and caches it in sys.modules, and that you can read relative and absolute imports inside a package.
What a circular import is
A circular import happens when module A imports module B, and module B (directly or through other modules) imports module A. Python does not reject this up front. It fails only when a name is used before it exists.
Recall that an import runs the module's code from top to bottom. Python adds the module to sys.modules before it runs that code. A second import of the same module therefore returns the half-built module object instead of starting over.
Why it fails
Suppose orders.py and customers.py import each other at module level.
# orders.py
from customers import discount_for
def total(order):
return order["amount"] - discount_for(order["customer"])# customers.py
from orders import total
def discount_for(name):
return 5Run import orders. The steps are:
- Python starts
ordersand registers it insys.modules. - The first line imports
customers, so Python starts runningcustomers.py. customers.pyrunsfrom orders import total.ordersis insys.modules, buttotalis not defined yet, becauseorders.pyis still on line 1.- Python raises
ImportError: cannot import name 'total' from partially initialized module 'orders'.
Plain import orders (without from) in customers.py would not fail at that line, because it only binds the module name. It fails later if you use orders.total before orders finishes loading.
Ways to break the cycle
Choose the least invasive fix that works.
| Fix | How | Trade-off |
|---|---|---|
| Move the import into a function | Import at call time | Hides the dependency, small cost per call |
| Import the module, not the name | `import customers`, then `customers.discount_for(...)` | Name is looked up late, so it works if used only inside functions |
| Extract shared code | Move the shared piece into a third module both import | Best structure, needs a refactor |
| Merge the modules | Combine tightly coupled code | Only for code that is really one unit |
The deferred import from the topic's example uses the first fix:
# orders.py
def total(order):
# Deferred import: customers.py also 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"])By the time total is called, both modules have finished loading, so the name exists.
Spotting a cycle
Read the traceback from the bottom. The message partially initialized module names the module that was still loading. The lines above it show the chain of imports that led back to it.
Exercise
a.py has from b import f on its first line and defines g afterward. b.py has from a import g on its first line. You run python -c "import a". Why does it fail, and what is the smallest change in b.py that fixes it, assuming b only uses g inside a function?
Show answer
Importing a registers it in sys.modules and starts a.py, which imports b. b.py then asks for g from a, but a is still on its first line and has not defined g, so Python raises ImportError (partially initialized module). Moving from a import g inside the function in b.py defers it until call time, when a has fully loaded. Using import a at the top of b.py and calling a.g() inside the function also works.