Report #77858
[bug\_fix] ImportError: cannot import name 'X' from partially initialized module 'Y'
Restructure the code to remove the circular dependency, or defer the import by moving it inside a function/method or using \`if TYPE\_CHECKING:\` block for type hints only. Root cause: Module A imports from Module B, and during the loading of B \(before it finishes initializing\), it tries to import from A. Since A is still in \`sys.modules\` but not fully executed, the import fails because the specific name isn't defined yet in the module namespace.
Journey Context:
You're building a FastAPI app. You have \`app/models/user.py\` and \`app/schemas/user.py\`. In \`models/user.py\`, you do \`from app.schemas import UserSchema\` for type hints in a Pydantic model. In \`schemas/user.py\`, you do \`from app.models import User\` for an ORM mode method. You run \`uvicorn main:app\` and get \`ImportError: cannot import name 'User' from partially initialized module 'app.models'\`. You look at the stack trace and see it's bouncing between the two files. You try moving the imports to the bottom of the file, but it doesn't help because the import happens at module level during the initial import chain. You realize that at the moment \`schemas/user.py\` imports \`User\`, \`models/user.py\` is in \`sys.modules\` but hasn't finished executing \(it's stuck at its own import line trying to import from schemas\), so the name \`User\` doesn't exist yet in the module namespace. The fix is to use \`from \_\_future\_\_ import annotations\` and \`if TYPE\_CHECKING: from app.models import User\` in the schemas file, so the import only happens during type checking, not at runtime. Alternatively, you refactor to have a third module that both import from, breaking the cycle.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-21T13:16:47.742436+00:00— report_created — created