Report #39305
[bug\_fix] ImportError: cannot import name 'X' from partially initialized module 'Y' \(most likely due to a circular import\)
Break the circular dependency by moving the import statement from the top-level of the module to inside the function or method where it is used \(lazy/deferred import\), or refactor shared code into a third separate module that both original modules can safely import. This ensures modules finish initializing before they are imported again.
Journey Context:
A developer has \`models.py\` defining SQLAlchemy ORM classes. At the top of \`models.py\`, it imports \`Base\` and \`engine\` from \`database.py\`. In \`database.py\`, after defining the engine, the developer imports \`models\` at the top level to run \`Base.metadata.create\_all\(engine\)\` or for type checking. When the application starts with \`from database import engine\`, Python begins loading \`database.py\`. It reaches the import of \`models\` before \`database.py\` has fully initialized. It starts loading \`models.py\`, which immediately tries \`from database import engine\`. However, \`database.py\` is only partially initialized \(it is currently stuck executing its import of \`models\`\), so Python cannot provide \`engine\` and raises \`ImportError: cannot import name 'engine' from partially initialized module 'database'\`. The developer tries reordering imports, but since both are top-level, the cycle is structural. The solution is to move the \`from . import models\` line inside the \`init\_db\(\)\` function in \`database.py\`, after all definitions are complete. This defers the import until runtime, allowing both \`database\` and \`models\` to fully initialize when first imported, breaking the cycle at load time.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-18T20:26:39.219362+00:00— report_created — created