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.

Introduction & Quick Summary
Python fails at import time with a message that names the cycle:
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.
# 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.
| Message | Raised by | Notes |
|---|---|---|
cannot import name 'X' from partially initialized module | from m import X | the most informative form |
partially initialized module 'm' has no attribute 'X' | m.X after import m | same cycle, later access |
cannot import name 'X' from 'm' | name genuinely absent | no circularity involved |
ModuleNotFoundError: No module named 'm' | path or install problem | unrelated to cycles |
Key Comparison Table
| Fix | Changes runtime behaviour | Effort | Correct when |
|---|---|---|---|
| Import inside the function | no, just defers | low | rare use, plugin hooks |
import module then attribute | no | low | the cycle is via names |
from __future__ import annotations | no | low | annotations are the only cycle |
| Extract a shared module | no | medium | both sides need the same types |
Lazy __getattr__ in a package | no | medium | public API re-exports |
| Merge the modules | simplifies | high | the 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.
# 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 moduleDeciding 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.
# 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.
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.
# 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__ againImport 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.
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.
# 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, orjson.pyin 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.pysets__name__to__main__and changes package semantics;python -m package.modelsfollows 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__.pystill imports, but the resolution order acrosssys.pathentries 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.
| Symptom | Cause | Fix |
|---|---|---|
error mentions __main__ | script execution | run with -m |
| works from REPL, fails from tests | different sys.path root | use an installed package layout |
| error names the stdlib module path | shadowed module name | rename the local file |
| error persists after a fix | stale bytecode or a second cycle | clear 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 documentationThe Python documentation that defines the behaviour this guide explains.
Try matching browser tools
All toolsSmall utilities that fit Python work — they run entirely in this browser tab, so nothing you paste leaves your device.
Related Python guides
All Python guidesasyncpg DuplicatePreparedStatement on PgBouncer and Supabase
asyncpg caches prepared statements per connection while a transaction pooler rotates connections underneath it. The cache setting, pool sizing and retry.
Python Tabulate: Markdown Grid Headers and Alignment
Use Python's tabulate library to format Markdown tables, set custom headers, and control column alignment with pipe and grid formats.
Handling Expired and Invalid Tokens with PyJWT in Python
Learn how to handle expired and invalid JWT tokens with PyJWT: catch ExpiredSignatureError, distinguish invalid tokens, and validate tokens safely in.
Python Cryptography: AES Symmetric Encryption
Implement AES symmetric encryption in Python with the cryptography library: key generation, CBC and GCM modes, padding, authentication, and key management.
More in Python
All Python guidesThe guides filed next to this one in Python, in library order.