Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

Python: ImportError from a partially initialized module

This circular import error appears when two modules import each other at load time. Move the import into a function, split shared code, or defer it.

~5 min readPython
#Python#Imports#Packaging#Debugging
Two Python module crates importing each other at a cyan gate, one amber half-built module card caught in the loop

Introduction & Quick Summary

Python fails at import time with a message that names the cycle:

code
ImportError: cannot import name 'User' from partially initialized module 'models' (most likely due to a circular import) (/app/models.py)

The module models was being executed when something imported it again. Python found the module object in sys.modules, but that object was still only half-built: execution had not reached the line that defines User yet. The import returns a partial module, and the name lookup fails.

The same condition produces a second message when the attribute is accessed instead of imported:

AttributeError: partially initialized module 'models' has no attribute 'User'

Two modules importing each other at module level is the cause. Either side alone is fine; together, whichever is imported first gets only a partially built partner.

Fixes, from smallest to largest:

  • Move the import inside the function that needs it.
  • Import the module (import models) and reference the attribute at call time.
  • Make the annotation-only dependency lazy with from __future__ import annotations.
  • Extract the shared code into a third module that neither side imports back.

Core Mechanics, Signatures & Reproducible Setup

Import executes top to bottom. import models creates the module object, inserts it into sys.modules, then runs the file. Any import statement inside that execution that reaches back to models gets the object from sys.modules without waiting, so names defined later do not exist yet.

python
# models.py from services import send_welcome # line 1: services is not finished yet class User: ... # services.py from models import User # this triggers the partially built module def send_welcome(user: User) -> None: ...

Running python -c "import models" reproduces it deterministically. The traceback shows the chain: models imported services, which imported models and asked for User.

MessageRaised byNotes
cannot import name 'X' from partially initialized modulefrom m import Xthe most informative form
partially initialized module 'm' has no attribute 'X'm.X after import msame cycle, later access
cannot import name 'X' from 'm'name genuinely absentno circularity involved
ModuleNotFoundError: No module named 'm'path or install problemunrelated to cycles

Key Comparison Table

FixChanges runtime behaviourEffortCorrect when
Import inside the functionno, just deferslowrare use, plugin hooks
import module then attributenolowthe cycle is via names
from __future__ import annotationsnolowannotations are the only cycle
Extract a shared modulenomediumboth sides need the same types
Lazy __getattr__ in a packagenomediumpublic API re-exports
Merge the modulessimplifieshighthe split was artificial

Practical Edge Cases, Error Fixes & Deep Dive Code Examples

1. Minimal reproduction and the real culprit

The traceback lists several frames and the first one is not always the cause. Read from the bottom: the last import is where the partial module was requested.

python
# a.py import b def hello(): return b.NAME # b.py import a # a is only partially initialized here NAME = a.hello() # AttributeError: partially initialized module

Deciding which import to defer is a design question: defer the one used in a function body, and keep the one needed at module level. That is why the cycle usually resolves by moving the consumer, not the definition.

2. Annotations are not runtime dependencies

With from __future__ import annotations, annotations are stored as strings and evaluated only by tools that ask for them. A cycle that exists purely through type hints disappears.

python
# orders.py from __future__ import annotations from typing import TYPE_CHECKING if TYPE_CHECKING: # imported by type checkers only from models import User def attach(user: User) -> None: # annotation is a string at runtime ...

This is the cleanest fix for FastAPI, SQLAlchemy 2.0, and Pydantic models that reference each other only in signatures.

3. Local imports for function-level use

When a module is needed only inside one call, importing there removes the load-time dependency and keeps the cost on the first call.

python
def send_welcome(user_id: str) -> None: from services.mailer import send # imported on first use send(user_id, template="welcome")

The trade-off is that the import error moves from startup to the call path, which is worse for production if the module is actually missing. Use it for genuine cycles, not to avoid fixing a dependency that is always needed.

4. Package __init__.py re-export loops

A package that re-exports submodules in __init__.py creates cycles when a submodule imports the package root.

python
# app/__init__.py from app.models import User # re-export from app.services import notify # services imports app.models... # app/services.py from app import User # triggers __init__ again

Import the concrete module instead (from app.models import User) inside submodules, and keep __init__.py limited to re-exports that do not feed back into the package.

5. Module versus name imports

import models binds the module object and defers attribute lookup to use time, while from models import User resolves the name immediately. Switching to the module form often breaks the cycle with no other change.

python
import models def make_user(row: dict) -> "models.User": return models.User(**row)

This is also what TYPE_CHECKING blocks rely on: the module name is enough for annotations.

6. Frameworks and registry imports

Django's app registry, Flask blueprints, and Celery task autodiscovery all import modules from configuration, which makes cycles appear only when the app starts, not when a single module is imported.

python
# tasks.py from celery import shared_task @shared_task def ping() -> str: from app.services import health # deferred: services imports tasks return health()

If the cycle involves framework startup, check the order in the settings or the app factory. Importing the application module from inside a task module that the application imports is the same cycle with extra machinery.

Common Compilation/Runtime Mistakes & Version Gotchas

  • Naming a module after a standard library module. email.py, types.py, or json.py in the project root shadows the stdlib and produces failures that look unrelated. The traceback shows the wrong module path.
  • Running a module as a script. python models.py sets __name__ to __main__ and changes package semantics; python -m package.models follows the package path. Cycles appear in one form and not the other.
  • Stale __pycache__. After renaming or moving a module, old bytecode can keep an outdated import graph alive. Delete the cache directory when the error does not match the source.
  • Namespace packages. A directory without __init__.py still imports, but the resolution order across sys.path entries is less obvious; two packages with the same name produce a partial module from the wrong location.
  • Python version differences. The wording and the exact point of failure changed across 3.10 to 3.13, so a message copied from an older article may not match what you see.
SymptomCauseFix
error mentions __main__script executionrun with -m
works from REPL, fails from testsdifferent sys.path rootuse an installed package layout
error names the stdlib module pathshadowed module namerename the local file
error persists after a fixstale bytecode or a second cycleclear caches, re-read traceback

Search the import chain with the regex tester when the traceback is long, and compare the two module versions with the text diff tool to see which import line introduced the cycle.

The import system, including sys.modules and partially initialized modules, is specified in the Python import reference, and the exception hierarchy for ImportError and ModuleNotFoundError is listed under built-in exceptions.

Official references

primary documentation

The Python documentation that defines the behaviour this guide explains.

Try matching browser tools

All tools

Small utilities that fit Python work — they run entirely in this browser tab, so nothing you paste leaves your device.

All Python guides

More in Python

All Python guides

The guides filed next to this one in Python, in library order.