- 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
You bump SQLAlchemy to 2.1 and a test that saves a new, unrefunded order fails with a TypeError. The bottom frame is your own Money.__post_init__. Above it, past the generated __init__, the frames belong to the ORM, because nobody in your code asked for a Money. Your adapter read row.refund, and SQLAlchemy tried to build one out of two Nones.
The 2.1 migration guide documents this: a composite attribute now returns an object "in all cases" by default. In 2.0, a pending object whose composite columns were all None gave you None.
The word that matters there is pending. A row loaded from the database never got that None in 2.0, so part of what you're about to fix was already broken.
The value object and the adapter
The domain file knows nothing about the database:
# domain.py
from dataclasses import dataclass
@dataclass(frozen=True)
class Money:
cents: int
currency: str
def __post_init__(self) -> None:
if self.cents < 0:
raise ValueError("negative amount")
if len(self.currency) != 3:
raise ValueError("currency needs 3 letters")
@dataclass(frozen=True)
class Order:
id: int
refund: Money | None = None
__post_init__ is called by the generated __init__, so Money(None, None) can't exist: comparing None < 0 raises TypeError. "No refund" is spelled None, in the type of Order.refund.
The row class maps Money as a composite over two nullable columns. This is the broken version:
# orders_sql.py
from sqlalchemy import Integer, String
from sqlalchemy.orm import (
DeclarativeBase,
Mapped,
Session,
composite,
mapped_column,
)
from domain import Money, Order
class Base(DeclarativeBase):
pass
class OrderRow(Base):
__tablename__ = "orders"
id: Mapped[int] = mapped_column(primary_key=True)
refund: Mapped[Money] = composite(
mapped_column("refund_cents", Integer, nullable=True),
mapped_column(
"refund_currency", String(3), nullable=True
),
)
The adapter, in the same file, maps that row to the domain type:
class SqlOrders:
def __init__(self, session: Session) -> None:
self._session = session
def get(self, order_id: int) -> Order | None:
row = self._session.get(OrderRow, order_id)
if row is None:
return None
return Order(row.id, row.refund)
def save(self, order: Order) -> None:
row = self._session.get(OrderRow, order.id)
if row is None:
row = OrderRow(id=order.id)
self._session.add(row)
if row.refund != order.refund:
row.refund = order.refund
Look at the last if. For a new row, row.refund is read on a pending object before anything has been assigned to it. On 2.1 that read fails for every new order, refunded or not, because it happens before the assignment.

Reading the attribute is enough to call the constructor.
Run the same probe on both versions
The probe inserts an all-NULL row with Core, so no ORM object is involved in setup, then reads the composite four ways:
# probe.py
import sqlalchemy
from sqlalchemy import create_engine, insert, select
from sqlalchemy.orm import Session
from orders_sql import Base, OrderRow
engine = create_engine("sqlite://")
Base.metadata.create_all(engine)
with engine.begin() as conn:
conn.execute(insert(OrderRow.__table__).values(id=1))
def pending(session):
return OrderRow(id=2).refund
def assigned(session):
return OrderRow(id=3, refund=None).refund
def loaded(session):
return session.get(OrderRow, 1).refund
def selected(session):
return session.scalar(select(OrderRow.refund))
print(sqlalchemy.__version__)
for case in (pending, assigned, loaded, selected):
with Session(engine) as session:
try:
print(case.__name__, repr(case(session)))
except Exception as exc:
print(case.__name__, type(exc).__name__, exc)
With uv you don't need two virtualenvs. These were the current releases of each series on November 30, 2026. 2.1 needs Python 3.11 or later.
uv run --no-project --python 3.13 \
--with 'sqlalchemy==2.0.58' probe.py
uv run --no-project --python 3.13 \
--with 'sqlalchemy==2.1.9' probe.py
I haven't run the probe or any other code in this post, so there's no pasted terminal output here. The table is read from descriptor_props.py at the two release tags: 2.0.58 and 2.1.9. The two commands above are how you check me.
Plain is Mapped[Money], optional is Mapped[Money | None].
| Case | 2.0.58, plain annotation | 2.1.9, plain annotation | 2.1.9, optional annotation |
|---|---|---|---|
| Pending, never assigned | None |
TypeError |
None |
Pending, assigned None
|
None |
None |
None |
| Loaded, both columns NULL | TypeError |
TypeError |
None |
select(OrderRow.refund) |
TypeError |
TypeError |
None |
Pending, never assigned. This is the one that moved. The 2.0.58 getter builds the composite only if state.key is not None or not _none_set.issuperset(values), meaning the object has an identity key or some column has a value. In 2.1.9 that guard is gone.
Pending, assigned None. The setter stores whatever you assigned, including None, and the getter returns the stored value without building anything. The stored value doesn't last: an after-insert handler drops it, and the next read rebuilds from the columns.
Loaded, and select() of the composite. The load handler in 2.0.58 checks that the columns are present, then calls Money. It never checks whether they're NULL. The row processor behind select(OrderRow.refund) has no NULL check either. Both cases raise on both versions, and the loaded one raises inside session.get(), before your mapping line runs.
So if your value object has an invariant and you have one integration test that reloads an order without a refund, that test was already failing on 2.0. If your tests only build and save rows through an adapter like this one, which reads row.refund before assigning it, they pass on 2.0 and break on 2.1.
If Money has no invariant, the upgrade is quieter. The pending read goes from None to a Money holding two Nones, and if row.refund is None takes the other branch without an exception.
The fix: put None in the annotation
2.1 added a return_none_on parameter to composite(). It takes a callable that receives the column values, and when it returns true the attribute is None. With Annotated Declarative you don't have to write it: an optional annotation sets a rule that returns None when all the columns are None.
In orders_sql.py, import CheckConstraint from sqlalchemy and replace the row class:
class OrderRow(Base):
__tablename__ = "orders"
__table_args__ = (
CheckConstraint(
"(refund_cents IS NULL)"
" = (refund_currency IS NULL)",
name="refund_all_or_nothing",
),
)
id: Mapped[int] = mapped_column(primary_key=True)
refund: Mapped[Money | None] = composite(
mapped_column("refund_cents", Integer, nullable=True),
mapped_column(
"refund_currency", String(3), nullable=True
),
)
Run the 2.1.9 probe again and you're in the last column of the table. SQLAlchemy's own composite tests assert the same three Nones, for a pending object, a persistent one and a direct select(), with an explicit return_none_on.
The check constraint is there because the automatic rule is all None. A row with 500 cents and no currency still reaches Money and fails there. That's the right outcome, since half a refund is corrupt data, but it's better rejected on write than discovered on read. On a table that already exists, the constraint needs a migration.

Both columns or neither. The constraint holds the pair together before the ORM sees it.
Two traps in that one-line change
Passing the class positionally turns the automatic rule off. This looks equivalent:
refund: Mapped[Money | None] = composite(
Money,
mapped_column("refund_cents", Integer, nullable=True),
mapped_column(
"refund_currency", String(3), nullable=True
),
)
In the 2.1.9 source, the code that reads | None sits inside if argument and self.composite_class is None. Pass Money as the first argument and the class is already known, so that block is skipped and no rule is installed. You're back to the TypeError. Either drop the argument or say it explicitly:
refund: Mapped[Money | None] = composite(
Money,
mapped_column("refund_cents", Integer, nullable=True),
mapped_column(
"refund_currency", String(3), nullable=True
),
return_none_on=lambda *v: all(x is None for x in v),
)
This trap matters most if you come from 2.0, because the positional form was a way to have the optional annotation there at all. The 2.0.58 code doesn't unwrap the union: in the shape without the positional class, loading a row raised 'types.UnionType' object is not callable. That issue is the ticket behind the 2.1 feature. Code that worked around it is the code the new rule skips.
Money | None doesn't make the columns nullable. A column's nullability comes from the dataclass field annotation, and cents: int means NOT NULL. An explicit nullable=True wins over the annotation, which is why both columns carry it. Don't loosen Money to int | None to get there. The domain type shouldn't change because a table has NULLs.
Pin it with pytest
Write one pytest test for each read that calls the constructor, against the real mapping:
# test_orders_sql.py
import pytest
from sqlalchemy import create_engine, insert, select
from sqlalchemy.exc import IntegrityError
from sqlalchemy.orm import Session
from domain import Money, Order
from orders_sql import Base, OrderRow, SqlOrders
@pytest.fixture
def engine():
engine = create_engine("sqlite://")
Base.metadata.create_all(engine)
with engine.begin() as conn:
conn.execute(insert(OrderRow.__table__).values(id=1))
yield engine
engine.dispose()
def test_pending_row_has_no_refund():
assert OrderRow(id=2).refund is None
def test_loaded_order_has_no_refund(engine):
with Session(engine) as session:
assert SqlOrders(session).get(1) == Order(1, None)
def test_selected_composite_is_none(engine):
with Session(engine) as session:
assert session.scalar(select(OrderRow.refund)) is None
The write path and the constraint go in the same file:
@pytest.mark.parametrize("refund", [None, Money(500, "EUR")])
def test_save_round_trip(engine, refund):
order = Order(2, refund)
with Session(engine) as session:
SqlOrders(session).save(order)
session.commit()
with Session(engine) as session:
assert SqlOrders(session).get(2) == order
def test_half_a_refund_is_rejected(engine):
half = insert(OrderRow.__table__).values(
id=3, refund_cents=500
)
with pytest.raises(IntegrityError):
with engine.begin() as conn:
conn.execute(half)
uv run --no-project --python 3.13 \
--with 'sqlalchemy==2.1.9' --with pytest \
python -m pytest -q
Keep the pending test separate from the others. A round trip through the adapter can't tell you which of the three reads broke, and the positional-class trap breaks all of them without changing the annotation a reviewer looks at.
Still on 2.0? Skip the composite
return_none_on doesn't exist in 2.0. If the same code has to run on both versions, map two plain columns and build the value object in the adapter:
class OrderRow(Base):
__tablename__ = "orders"
# keep __table_args__ from above
id: Mapped[int] = mapped_column(primary_key=True)
refund_cents: Mapped[int | None]
refund_currency: Mapped[str | None] = mapped_column(
String(3)
)
def refund_of(row: OrderRow) -> Money | None:
cents, currency = row.refund_cents, row.refund_currency
if cents is None and currency is None:
return None
return Money(cents, currency)
get() returns Order(row.id, refund_of(row)), and save() writes the two columns. You lose select(OrderRow.refund). In exchange, the "no refund" rule is four lines of your code, and the ORM never calls your constructor. Keep the check constraint either way, and swap the pending and select() tests for assertions on refund_of.
Before you bump the pin, search your adapters for composite(. For each hit, ask whether the columns can all be NULL, and write the pending test first. On 2.0.58 it passes without | None, which is why a suite that only builds and saves rows never complained.
If this was useful
A domain type that refuses to exist half-built only helps if the adapter knows how to say "nothing here." Hexagonal Architecture in Python is about that boundary: it builds an async FastAPI and SQLAlchemy 2 booking service as a hexagon, then compares one feature built five ways (Hexagonal, Clean, Onion, layered and vertical slice), with measurements. Every listing that names a repo path comes from the free companion repo, and the SQLAlchemy adapters are in its roombook service.

Top comments (1)
Gabriel, the row of your table that matters most is the one that did not move: 'Loaded, both columns NULL' is a TypeError on 2.0.58 and on 2.1.9. Everything else in the post is about what the upgrade changed, but that row is the one that was already broken โ and it raises inside session.get(), before your mapping line even runs, so no adapter-level guard catches it.
That makes one line of your pre-bump advice worth tightening: 'write the pending test first' is right, but a pending-only suite would still pass on 2.0 and leave the loaded path untested. The probe you give โ insert the all-NULL row with Core, then session.get() โ is the test that actually has to exist before the bump, because it is the only one that fails on both versions. The pending test catches the regression; the loaded test catches the bug you already had.
One question on the check constraint: it rejects half-refunds (500 cents, no currency) at the database, which is the right place โ but only for new writes. If a table already has a few half-refund rows from the 2.0 era, adding the constraint fails the migration. Would you validate existing data first (a quick query for rows where one of the two columns is NULL and the other is not) and backfill or flag those rows before the constraint goes in, or let the migration fail loudly as the discovery mechanism?