- Book: Hexagonal Architecture in Python
- Companion code: hexagonal-python-examples — every listing from the book, free on GitHub
- My project: Hermes IDE | GitHub — an IDE for developers who ship with Claude Code and other AI coding tools
- Me: xgabriel.com | GitHub
The line is from sqlalchemy import select, and it sits at the top of shop/orders/domain/order.py. A coding agent put it there while adding a "find orders above a threshold" query to your FastAPI service, because the Order class lived in that file and the import was the shortest path to a working query. The tests stayed green, and a reviewer skimming twelve lines of diff on a Friday approved it.
That one line is where the hexagon starts to dissolve. Your domain now depends on your database library, and the next change will lean on it, because the import is already there.
A folder called domain/ is a convention. Conventions hold while everyone remembers them, and an agent has no memory of the architecture talk you gave last quarter. You need a check that fails the build. import-linter does that: you declare rules about which modules may import which, and lint-imports exits non-zero when a rule breaks. Three contracts in pyproject.toml cover the usual leaks, and the same command runs on your laptop and in GitHub Actions.
The sample project
Two features, each with the same three subpackages, plus a composition root:
shop/
__init__.py
db.py
main.py
orders/
__init__.py
domain/ __init__.py, order.py
application/ __init__.py, ports.py, place_order.py
adapters/ __init__.py, sql.py, http.py
billing/
__init__.py
domain/ __init__.py, invoice.py
application/ __init__.py
adapters/ __init__.py
pyproject.toml
The domain is a plain dataclass. No framework, no ORM:
# shop/orders/domain/order.py
from dataclasses import dataclass
@dataclass(frozen=True)
class Order:
id: str
total_cents: int
def __post_init__(self) -> None:
if self.total_cents <= 0:
raise ValueError("an order needs a positive total")
The application layer owns the port, a typing.Protocol, and the use case that depends on it:
# shop/orders/application/ports.py
from typing import Protocol
from shop.orders.domain.order import Order
class OrderRepository(Protocol):
async def add(self, order: Order) -> None: ...
async def get(self, order_id: str) -> Order | None: ...
# shop/orders/application/place_order.py
import uuid
from shop.orders.application.ports import OrderRepository
from shop.orders.domain.order import Order
class PlaceOrder:
def __init__(self, repo: OrderRepository) -> None:
self._repo = repo
async def __call__(self, total_cents: int) -> Order:
order = Order(id=str(uuid.uuid4()), total_cents=total_cents)
await self._repo.add(order)
return order
The adapters are where SQLAlchemy 2 and FastAPI live. The SQL adapter maps rows to domain objects:
# shop/orders/adapters/sql.py
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column
from shop.orders.domain.order import Order
class Base(DeclarativeBase):
pass
class OrderRow(Base):
__tablename__ = "orders"
id: Mapped[str] = mapped_column(primary_key=True)
total_cents: Mapped[int]
OrderRow is the ORM model, and it never leaves this file. The repository in the same module translates it to and from the domain Order:
# shop/orders/adapters/sql.py (continued)
class SqlOrderRepository:
def __init__(self, session: AsyncSession) -> None:
self._session = session
async def add(self, order: Order) -> None:
row = OrderRow(id=order.id, total_cents=order.total_cents)
self._session.add(row)
await self._session.commit()
async def get(self, order_id: str) -> Order | None:
row = await self._session.scalar(
select(OrderRow).where(OrderRow.id == order_id)
)
if row is None:
return None
return Order(id=row.id, total_cents=row.total_cents)
The HTTP adapter uses Pydantic models at the edge and FastAPI's Depends to wire the use case to the SQL adapter:
# shop/orders/adapters/http.py
from collections.abc import AsyncIterator
from fastapi import APIRouter, Depends
from pydantic import BaseModel
from sqlalchemy.ext.asyncio import AsyncSession
from shop.db import session_factory
from shop.orders.adapters.sql import SqlOrderRepository
from shop.orders.application.place_order import PlaceOrder
router = APIRouter()
class PlaceOrderIn(BaseModel):
total_cents: int
class OrderOut(BaseModel):
id: str
total_cents: int
async def get_session() -> AsyncIterator[AsyncSession]:
async with session_factory() as session:
yield session
def get_place_order(
session: AsyncSession = Depends(get_session),
) -> PlaceOrder:
return PlaceOrder(SqlOrderRepository(session))
The dependency builds the use case per request, so the route only ever sees PlaceOrder:
# shop/orders/adapters/http.py (continued)
@router.post("/orders", status_code=201)
async def place_order(
body: PlaceOrderIn,
use_case: PlaceOrder = Depends(get_place_order),
) -> OrderOut:
order = await use_case(body.total_cents)
return OrderOut(id=order.id, total_cents=order.total_cents)
And the two files outside the features, the engine and the app:
# shop/db.py
from sqlalchemy.ext.asyncio import (
async_sessionmaker,
create_async_engine,
)
engine = create_async_engine("sqlite+aiosqlite:///./shop.db")
session_factory = async_sessionmaker(engine, expire_on_commit=False)
# shop/main.py
from contextlib import asynccontextmanager
from fastapi import FastAPI
from shop.db import engine
from shop.orders.adapters.http import router as orders_router
from shop.orders.adapters.sql import Base
@asynccontextmanager
async def lifespan(app: FastAPI):
async with engine.begin() as conn:
await conn.run_sync(Base.metadata.create_all)
yield
app = FastAPI(lifespan=lifespan)
app.include_router(orders_router)
billing has the same three subpackages with an Invoice dataclass in domain/invoice.py and empty __init__.py files elsewhere. It exists so the third contract has something to keep apart. Run the app with uvicorn shop.main:app --reload.
Install import-linter and set up pyproject.toml
The current release is 2.17, published on November 18, 2026, and it needs Python 3.11 or newer. The install docs recommend it as a dev dependency. One thing you may notice on PyPI: 2.17 carries a provenance-change notice, because the project moved to the import-linter GitHub organization in that release.
[build-system]
requires = ["setuptools>=69"]
build-backend = "setuptools.build_meta"
[project]
name = "shop"
version = "0.1.0"
requires-python = ">=3.11"
dependencies = [
"fastapi",
"uvicorn",
"sqlalchemy[asyncio]",
"aiosqlite",
]
[project.optional-dependencies]
dev = ["import-linter>=2.17", "pytest"]
[tool.setuptools.packages.find]
include = ["shop*"]
[tool.importlinter]
root_package = "shop"
include_external_packages = true
root_package is the import name of the package to check. include_external_packages = true matters here: the forbidden contract docs say it is required whenever a contract names an external package such as sqlalchemy. Grimp, the graph library underneath, adds each external package as a single squashed node, so you name it by its top-level package. The docs say so directly: django is allowed, django.db.models is not.
Three contracts
Each contract closes one way the hexagon leaks: a layer importing upward, the domain importing a framework, and one feature importing another.

Imports may point inward, toward the domain. The layers contract blocks the ones that point out.
Layers inside each feature
[[tool.importlinter.contracts]]
name = "Each feature: adapters > application > domain"
type = "layers"
containers = ["shop.orders", "shop.billing"]
layers = ["adapters", "application", "domain"]
exhaustive = true
The layers contract reads its list from higher to lower. A higher layer may import anything below it. A lower layer may not import anything above it. With containers set, the layer names are relative to each container, so this one rule covers shop.orders.domain and shop.billing.domain alike.
The check includes indirect imports. If domain imports a helper module that imports adapters.sql, the chain counts as a break even though domain never names the adapter.
exhaustive = true makes the contract fail when a container holds a child module the list does not declare (it only works together with containers). That earns its keep with agents: when one creates shop/orders/utils/ to stash a shortcut, the build tells you, and you decide which layer it belongs to.
The domain stays framework-free
[[tool.importlinter.contracts]]
name = "Domain stays framework-free"
type = "forbidden"
source_modules = ["shop.*.domain"]
forbidden_modules = ["fastapi", "sqlalchemy"]
broken_contract_guidance = """
Domain code must not touch FastAPI or SQLAlchemy.
Define a port in application/ports.py and
implement it in adapters/sql.py instead."""
The layers contract only knows about your own modules. This forbidden contract covers the third-party ones. shop.*.domain is a wildcard: * stands for one module name, so it matches every feature's domain package, and a new shop.shipping.domain is covered the day it appears. Indirect imports count here too unless you set allow_indirect_imports, so a domain module that imports shop.db gets caught through shop.db's own SQLAlchemy import.
broken_contract_guidance arrived in 2.14. It prints your message below the built-in one when the contract breaks. For a human, it saves a trip to the wiki. For a coding agent reading the CI log, it is the fix instruction, written by you, sitting right next to the error.
Features stay independent
[[tool.importlinter.contracts]]
name = "Features don't import each other"
type = "independence"
modules = ["shop.orders", "shop.billing"]
The independence contract checks that there are no imports in any direction between the listed modules, "even indirectly". If billing needs to react to a placed order, the two features talk through something you own on purpose (an event, a shared kernel module, the composition root), and that decision shows up in a reviewable place.
List the features explicitly. A wildcard like shop.* would also match shop.main and shop.db, and main has to import the features to wire them.
Run it, break it, read the failure
Locally, from the project root:
pip install -e ".[dev]"
lint-imports
lint-imports adds the current directory to sys.path before it builds the graph, and it returns exit code 0 on success and 1 otherwise. That exit code is all CI needs:
# .github/workflows/architecture.yml
name: architecture
on:
pull_request:
push:
branches: [main]
jobs:
import-contracts:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v7
- uses: actions/setup-python@v7
with:
python-version: "3.13"
- run: pip install -e ".[dev]"
- run: lint-imports --no-logo
--no-logo (added in 2.14) drops the ASCII banner that 2.7 introduced along with rich output, which keeps the CI log short. The action versions are the current majors: checkout v7 and setup-python v7.

The CI job is a gate every pull request passes through, whoever wrote it.
Now replay the opening scene. The agent's edit leaves order.py starting like this:
from dataclasses import dataclass
from sqlalchemy import select
The layers contract still passes (SQLAlchemy is not one of your layers), and so does the independence contract. The forbidden contract breaks. I haven't run this exact project myself, so I won't paste a terminal capture. Here is what the forbidden contract's renderer builds for this break: a header from the format string {downstream} is not allowed to import {upstream}:, a blank line, then the first link of the chain as {importer} -> {imported} ({line_numbers}) with a dash and three spaces in front of it:
shop.orders.domain is not allowed to import sqlalchemy:
- shop.orders.domain.order -> sqlalchemy (l.3)
Your broken_contract_guidance text prints under it. Around those lines, the rich output adds the contract list with each contract's status and a summary count; the layout of that frame has changed across versions, so check it against your own run. For an indirect break, the chain gets one line per hop, the first prefixed with - and the rest indented, each with its line number.
The step goes red, and with a required check the pull request can't merge. The log points at the file and the line, and your guidance text says what to do instead.
When you need an exception
Sometimes a break is deliberate and temporary. All three contract types here take ignore_imports, a list of importer -> imported lines that also accepts wildcards:
ignore_imports = [
"shop.orders.domain.legacy -> sqlalchemy",
]
Two defaults keep the exceptions honest. unmatched_ignore_imports_alerting is error by default, so when someone deletes the legacy import and forgets the ignore line, the build fails until the stale exception goes too. And since 2.16, an unrecognized contract option is an error, so a typo like exhastive = true fails the run instead of quietly leaving the exhaustiveness check off.
Start with these three contracts on a project that already passes them. Then make the workflow a required status check. From then on, nobody has to remember where the boundary is, and neither does the agent.
If this was useful
These contracts encode one shape. Hexagonal Architecture in Python builds one async FastAPI + SQLAlchemy 2 service five ways (Hexagonal, Clean, Onion, layered and vertical slice), then measures them. If you are deciding where your own boundaries go before you write contracts for them, that comparison is the useful part. Every listing runs from the free companion repo.

Top comments (1)
Using
exhaustive = truealongsidebroken_contract_guidanceis a great combination for keeping coding agents inside the hexagon—putting the fix instruction directly in the CI failure output saves a whole round-trip when an agent reads the logs. One subtle Python edge case to watch in yourOrder.__post_init__check (if self.total_cents <= 0) is thatboolsubclassesint, so an upstream payload passingtotal_cents=Trueevaluates as1 > 0and slips right past the guard unless explicitly rejected:Also, while Grimp's AST scan catches function-scoped lazy imports, pairing
lint-importswith a quick CI check againstimportlib.import_moduleprevents an agent from routing around a forbidden module dynamically.