Circular Imports Fail at Import Time, So Shared Objects Belong in a Module Neither Side Imports

In progress Python FastAPI

Python runs a module's top-level code the first time it is imported. When main.py imports a router module that imports something back from main.py, the second import finds main only half executed, and the name it wants doesn't exist yet: ImportError: cannot import name ... from partially initialized module. The cure is structural: move what both sides need into a third module, or, when the cycle exists only for type hints, keep those imports out of runtime.

Case 1: Routers Importing from the App

main.py ──imports──> routes/notes.py
   ▲                       │
   └──imports templates────┘

main.py creates the app and templates = Jinja2Templates(...), then imports the router to register it; the router imports templates from main. Extract the shared object:

# config/templates.py: imports neither main nor routes
from pathlib import Path
from fastapi.templating import Jinja2Templates

templates = Jinja2Templates(directory=Path(__file__).resolve().parent.parent / "templates")

Both main.py and routes/notes.py import from config.templates; the dependency graph becomes a tree. The same goes for settings, database engines and loggers.

Case 2: Models That Reference Each Other

Two SQLModel (or SQLAlchemy) models with a relationship in both directions import each other:

# models/task.py
from typing import TYPE_CHECKING
from sqlmodel import Field, Relationship, SQLModel

if TYPE_CHECKING:
    from models.user import User

class Task(SQLModel, table=True):
    id: int | None = Field(default=None, primary_key=True)
    user_id: int | None = Field(default=None, foreign_key="user.id")
    user: "User" = Relationship(back_populates="tasks")

TYPE_CHECKING is False at runtime, so the import only happens for type checkers and editors; the quoted annotation "User" is resolved later by the ORM from its registry. models/user.py does the same for Task.

References

Review cards

Flashcard Why does a router that imports `templates` from `main.py` raise `ImportError`?

main.py imports the router before it's finished, so the router finds main partially initialised, without templates yet. Moving templates to a module neither imports (config/templates.py) breaks the cycle.

Flashcard How does `if TYPE_CHECKING:` break an import cycle between two models?

TYPE_CHECKING is False at runtime, so the import only happens for type checkers and editors. The quoted annotation ("User") is resolved later by the ORM from its registry.

Quiz How should you fix the cycle between `main.py` and `routes/notes.py` over `templates`?
  • Move templates into config/templates.py and import it from both
  • Keep templates in main.py and import it in the router
  • Import templates under if TYPE_CHECKING: in the router
  • Import templates inside the route function

The router needs templates at runtime, so TYPE_CHECKING won't do. A local import silences the error but keeps the modules tangled; the third module makes dependencies point one way.

Flashcard Why is moving an import inside a function a poor fix for a circular import?

It silences the error but leaves the two modules tangled. A third module or TYPE_CHECKING makes the dependency direction explicit: entry points import routers, nothing imports the entry point.