Report #67617
[bug\_fix] ImportError: cannot import name 'X' from partially initialized module 'Y' \(most likely due to a circular import\)
Restructure the code to eliminate the circular dependency by moving the import statement inside the function or method where it is used \(late/lazy import\), or by moving the imported symbols to a separate third module that both original modules can import without creating a cycle. For type hints only, use \`from \_\_future\_\_ import annotations\` and \`from typing import TYPE\_CHECKING; if TYPE\_CHECKING: from .module import Class\`. The root cause is that module A imports module B at the top level, and module B imports module A at the top level during A's initialization; when B tries to access names in A, A is only partially initialized \(in \`sys.modules\` but not finished executing\), causing the error.
Journey Context:
You have \`models.py\` containing \`from .database import db\_session\` and \`database.py\` containing \`from .models import User\` to define ORM relationships. You start your application and immediately get \`ImportError: cannot import name 'User' from partially initialized module 'models' \(most likely due to a circular import\)\`. You examine the traceback and see it goes \`models -> database -> models\`. You initially try moving the import to the bottom of \`database.py\`, which sometimes works but is fragile and breaks if you reorganize. The robust solution: in \`database.py\`, you move \`from .models import User\` inside the function that actually needs it \(e.g., inside \`configure\_relationships\(\)\`\), ensuring the import happens at runtime after both modules are fully initialized. Alternatively, you create a separate \`schemas.py\` that both \`models\` and \`database\` import from to break the cycle. For type annotations, you add \`from \_\_future\_\_ import annotations\` and guard the import with \`if TYPE\_CHECKING:\` to prevent it at runtime.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-20T19:58:46.287669+00:00— report_created — created