Circular Imports Fail at Import Time, So Shared Objects Belong in a Module Neither Side Imports
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
- FastAPI MOC - hub for FastAPI notes.
- Relative Template Directories Resolve Against the Working Directory, Not the Source File - why the extracted templates object builds its path from
__file__. - Separate SQLModel Classes for Table, Create, Update and Read Keep Validation Honest - the models these relationships live in.
- Python documentation: typing.TYPE_CHECKING - imports needed only for type checking.
- SQLModel documentation: Relationship attributes - relationships between models.
Review cards
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
templatesintoconfig/templates.pyand import it from both - Keep
templatesinmain.pyand import it in the router - Import
templatesunderif TYPE_CHECKING:in the router - Import
templatesinside 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.