Report #54164
[bug\_fix] ImportError: cannot import name 'Utility' from partially initialized module 'app.utils' \(most likely due to a circular import\)
The root cause is that during the import of module A, its top-level code imports module B, which in turn tries to import A \(or a submodule of A\) before A has finished executing. Python inserts A into sys.modules at the start of the import to prevent infinite recursion, but the module object is only partially initialized \(its code hasn't finished running\), so attributes like classes or functions don't exist yet. The fix is to refactor the code to remove the circular dependency \(e.g., merge modules, use dependency injection\), or move the import statement inside the function/method where it's used \(lazy import\) so it executes after both modules are fully initialized.
Journey Context:
Developer has \`app/models.py\` containing \`from app.utils import save\_model\` at the top, and \`app/utils.py\` containing \`from app.models import BaseModel\` at the top of both files. They run \`python -m app.main\` and get \`ImportError: cannot import name 'save\_model' from partially initialized module 'app.utils'\`. Developer is confused because both files exist. They try reordering imports. They inspect \`sys.modules\` during debugging and see \`'app.models'\` exists but is an empty module object. They realize that when \`app.models\` starts importing, it triggers \`app.utils\`, which then tries to import \`app.models\` again. Since \`app.models\` is already in \`sys.modules\` \(but not finished executing\), Python returns the partial module which doesn't yet have \`BaseModel\` defined. The developer moves the import in \`utils.py\` inside the function that uses \`BaseModel\`, breaking the cycle at import time, allowing both modules to fully initialize before the function \(and its import\) is called.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-19T21:24:43.363021+00:00— report_created — created