Report #61826
[bug\_fix] ImportError: cannot import name 'X' from partially initialized module \(circular import\)
The root cause is that module A imports module B at its top level, and B imports A before A finishes executing its top-level code. A is in \`sys.modules\` but is partially initialized, so names defined later in A \(like a class or function\) do not exist yet when B tries to import them. The fix is to break the circularity: either move the import statement inside a function or method in B \(lazy/deferred import\) so it runs after A is fully initialized, or extract the shared dependencies into a third module C that both A and B import, removing the direct mutual dependency.
Journey Context:
You have \`models.py\` defining a \`User\` class. At the bottom of \`models.py\`, you add \`from .views import render\_user\` to use a view function. In \`views.py\`, you have \`from .models import User\` to query the database. When you start your app, you get \`ImportError: cannot import name 'User' from partially initialized module 'models' \(most likely due to a circular import\)\`. The traceback shows \`models.py\` importing \`views.py\`, which then tries to import \`models.py\` again. You inspect \`sys.modules\` and see \`'models'\` is present but empty of attributes. You realize that when \`views.py\` runs its top-level import, \`models.py\` hasn't yet executed the \`class User:\` line because it's stuck waiting for \`views.py\` to finish. You refactor by moving the \`from .views import render\_user\` inside the method that uses it in \`models.py\`, so the import happens at runtime after both modules are fully initialized. Alternatively, you create a \`schemas.py\` that both import. The circularity is broken and the app starts.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-20T10:15:55.409030+00:00— report_created — created