Report #84052
[bug\_fix] ImportError: cannot import name 'X' from partially initialized module \(circular import\)
Refactor to break the circular dependency. Options: 1\) Move the import statement inside the function/method where it is used \(lazy import\) to defer execution until after both modules are fully initialized. 2\) Use \`if TYPE\_CHECKING: from .module import Type\` for type hints only. 3\) Merge the two modules or extract the shared dependency into a third module imported by both. Root cause: Module A imports Module B at the top level; Module B imports Module C \(or back to A\) before A has finished executing its top-level code, so A's namespace is incomplete \(partially initialized\) when B tries to import names from it.
Journey Context:
A developer is building a FastAPI application. They have a \`schemas.py\` defining Pydantic models for API requests, and a \`models.py\` containing SQLAlchemy ORM classes. In \`schemas.py\`, they add \`from .models import UserORM\` to use in a \`from\_orm\` method. In \`models.py\`, they decide to add a property that returns a Pydantic schema, so they add \`from .schemas import UserSchema\`. When they start the application with \`uvicorn\`, it crashes with \`ImportError: cannot import name 'UserORM' from partially initialized module 'app.models'\`. The developer is confused because both files exist and the names are correct. They try reordering the imports, moving the \`from .models\` line to the bottom of \`schemas.py\`, but the error persists or moves. They try adding \`import app.models\` instead of \`from\`, same issue. They eventually learn that when Python starts importing \`models\`, it executes top-level code, hits \`from .schemas import UserSchema\`, switches to importing \`schemas\`, which hits \`from .models import UserORM\`. But \`models\` is not yet fully initialized \(it's in \`sys.modules\` but its namespace is empty\), so the import fails. The developer fixes it by moving the import inside the method in \`models.py\` that uses it, so the import happens at runtime after both modules are fully initialized, breaking the circularity at import time.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-21T23:40:33.926473+00:00— report_created — created