All articles

Circular Imports in Python: Why They Happen and How to Fix Them

Circular Imports in Python: Why They Happen and How to Fix Them

A syntax error or a typo in a variable name is easy to find. A circular import in Python is a different story: two modules reference each other, and the program crashes with a message that explains almost nothing. In a two-file project the cause is obvious. In a project with dozens of modules and packages the cycle can run through five files, and it's much harder to track down.

Let's look at why circular imports happen, how to read the error, which fixes work, and which import traps come up most often.

What a circular import looks like

Two modules: alerts.py sends notifications and sometimes looks up a user, while users.py works with users and writes notifications.

# alerts.py
from users import get_user


def notify(msg):
    print("NOTIFY", msg)
# users.py
from alerts import notify


def get_user(uid):
    notify(f"get {uid}")
    return {"id": uid}

Run import alerts and you get:

ImportError: cannot import name 'notify' from partially initialized module 'alerts'
(most likely due to a circular import)

The wording may differ in recent Python versions, but the meaning is the same.

Why it happens

A module runs from top to bottom. When Python hits an import, it:

  1. Looks for the module in the sys.modules cache. If it's already there, it returns it right away — even if it hasn't finished loading.
  2. If the module isn't there, it creates an empty module object, puts it in sys.modules and starts executing the file's code.

Now step by step. Python starts executing alerts.py and on the first line goes to users.py. That file asks for notify from alerts on its first line. The alerts module is already in sys.modules, but it has only executed up to its first line — the notify function isn't defined yet. No name — ImportError.

Important: Python doesn't spin in an endless loop or overflow the stack. Thanks to the cache, a repeated import immediately returns the partially initialized module. The error is that you ask it for a name that hasn't been created yet.

Fix 1: import the module, not the name

The simplest fix is to import the whole module and access the function with a dot:

# alerts.py
import users


def notify(msg):
    print("NOTIFY", msg)


def audit(uid):
    notify(users.get_user(uid))
# users.py
import alerts


def get_user(uid):
    alerts.notify(f"get {uid}")
    return {"id": uid}

import users just stores a reference to the module, and the users.get_user attribute is looked up only when the function is called, by which time both modules are loaded. This works as long as the modules don't use each other at the top level — for example, they don't call the neighbor's functions right at import time.

Fix 2: import inside a function

You can move the import into the function that needs it:

def audit(uid):
    from users import get_user  # runs on call, not when the module loads
    notify(get_user(uid))

The Python documentation allows this, and repeated calls are cheap: the module comes from the cache. But don't overuse it — PEP 8 says imports go at the top of the file, and hidden dependencies make code harder to read. Use it as a temporary fix when there's no time to refactor a large project.

Fix 3: imports only for type annotations

Type hints are a common source of cycles. The Order class references Customer, and Customer keeps a list of Order objects, even though it actually needs Order only for an annotation. That's what TYPE_CHECKING is for:

# customer.py
from __future__ import annotations

from typing import TYPE_CHECKING

if TYPE_CHECKING:
    from order import Order


class Customer:
    def __init__(self, name: str) -> None:
        self.name = name
        self.orders: list[Order] = []
# order.py
from customer import Customer


class Order:
    def __init__(self, customer: Customer) -> None:
        self.customer = customer
        customer.orders.append(self)

TYPE_CHECKING is False at runtime, so the import happens only during type checking in mypy or an IDE. from __future__ import annotations postpones evaluating annotations, so the name Order isn't needed when the module loads.

Fix 4: the right solution — remove the cycle from the architecture

All the previous methods work around the symptom. Most often a circular import is a sign that two modules know too much about each other. The reliable solution is to move shared code into a third module that both depend on, or to invert the dependency: for example, pass the notification function into users as a parameter instead of importing it.

alerts.py ─┐
           ├──> common.py   (shared functions and types)
users.py ──┘

When dependencies point in one direction, the cycle disappears by itself.

Trap: a file named like a standard module

The simplest script:

# webbrowser.py
import webbrowser

webbrowser.open("https://duckduckgo.com")

You wanted to move browser handling into its own module and named the file the same as the standard module. The result: AttributeError: module 'webbrowser' has no attribute 'open'. Python looks for modules in the running script's directory first, so import webbrowser imports your own file rather than the standard library. Recent Python versions explicitly suggest renaming the file, but in older ones you'll have to figure it out yourself. Don't name your modules random.py, email.py, json.py, webbrowser.py and so on.

Trap: cycles inside a package and import *

In packages, a cycle often hides in __init__.py. If __init__.py imports report, report imports scan, and scan reaches back into report for a function that isn't defined yet, you get the same ImportError. What helps is an explicit, well-thought-out import order in __init__.py and the rule that submodules shouldn't import each other in a circle.

A separate word about from module import *. It pulls everything into your namespace, easily creates cycles and silently overwrites names: if both modules have a test function, it's unclear which one will be called. Import what you need explicitly.

What changed across Python versions

Import behavior improved gradually. Python 3.5 learned to resolve some cycles involving package submodules: from package import module now finds a partially loaded submodule in sys.modules. In Python 3.7 the same started working for import a.b as c. And error messages get clearer with every version. But the fundamental rule hasn't changed: you can't take a name from a module before it has been created.

Summary

Situation Solution
Two modules import names from each other import module instead of from module import name
A cycle in a large project, need a quick fix Import inside a function
The import is only needed for annotations TYPE_CHECKING and from __future__ import annotations
Modules are too tightly coupled Move shared code into a third module
A strange AttributeError on a standard module Rename your file

Circular imports almost always signal architecture problems, and the best prevention is a thoughtful split into modules and layers. How to structure a project so that dependencies point in one direction is covered in detail in my Python OOP course. And another non-obvious Python pitfall — how lists consume memory — is explained in why a Python list can eat all your memory.

Sources