skip to content

After a team moves its SQLAlchemy 2.1 models to MappedAsDataclass, what changes about constructors, defaults and the instance __dict__, and what breaks first?

level: seniorimportance: should knowfreq 30%

answer

  1. a generated __init__ per class
  2. generated keys stay out of __init__
  3. required fields before defaulted ones
  4. a sentinel instead of the stored default

basics

~20 s

MappedAsDataclass makes each mapped class a real dataclass with generated init(), repr() and eq(). Generated keys need init=False, defaults move into mapped_column(default=...), and in 2.1 those defaults reach the attribute through its descriptor rather than dict.

solid answer

~40 s

Adding `MappedAsDataclass` to the base runs the dataclass machinery on every mapped class. The keyword-only declarative constructor becomes a generated `__init__()` that follows field order, so a database-generated `id` needs `mapped_column(primary_key=True, init=False)` or it becomes a required argument, and a field without a default after a defaulted one fails class creation (`InvalidRequestError` wrapping the dataclass `TypeError`) unless you reorder or set `kw_only=True`. Defaults are written as `mapped_column(default=...)` or `default_factory=`, never inside an `Annotated` alias. In SQLAlchemy 2.1, `__init__()` uses the `DONT_SET` sentinel and a `default=` value is not stored in `__dict__`: the descriptor returns it on access and the INSERT still sends it, so code reading `vars(obj)` misses it until the flush. Generated `__eq__()` compares fields and leaves instances unhashable unless `eq=False`.

code

python · 40 lines
python
import datetime
import inspect

from sqlalchemy import String, create_engine, func
from sqlalchemy.orm import (
    DeclarativeBase,
    Mapped,
    MappedAsDataclass,
    Session,
    mapped_column,
)


class Base(MappedAsDataclass, DeclarativeBase):
    pass


class Account(Base):
    __tablename__ = "account"

    id: Mapped[int] = mapped_column(primary_key=True, init=False)
    email: Mapped[str] = mapped_column(String(255))
    bio: Mapped[str | None] = mapped_column(default=None)
    status: Mapped[str] = mapped_column(String(20), default="active")
    created_at: Mapped[datetime.datetime] = mapped_column(
        insert_default=func.now(), init=False
    )


print(inspect.signature(Account.__init__))
account = Account("[email protected]")
print(account)
print(sorted(k for k in vars(account) if not k.startswith("_")))

engine = create_engine("sqlite://")
Base.metadata.create_all(engine)
with Session(engine) as session, session.begin():
    session.add(account)
    session.flush()
    print(account.id, account.status, type(account.created_at).__name__)

go deeper

for a junior

Recall that MappedAsDataclass generates init(), repr() and eq(), and that a database-generated id needs init=False.

for a middle

Explain the field options on mapped_column(), why defaults are not placed in Annotated templates, and how field order and kw_only shape the generated constructor.

for a senior

Walk through what breaks during a migration: required ids, ordering failures and plain mixins rejected at import, vars()-based serialisers missing 2.1 descriptor defaults, unhashable instances.

for a principal

Weigh dataclass constructors and type-checker support against the migration cost and the eq and hash semantics, and set the base's options once so every team inherits the same behaviour.

## What the mixin does `MappedAsDataclass` is a mixin placed on the declarative base (or on one class): `class Base(MappedAsDataclass, DeclarativeBase)`. After each subclass is mapped, SQLAlchemy runs Python's own dataclass machinery on it, so the class gains a generated **`__init__()`**, **`__repr__()`** and **`__eq__()`**, and type checkers treat it as a dataclass. Class-level options `init`, `repr`, `eq`, `order`, `unsafe_hash`, `match_args` and `kw_only` are supported; `frozen` and `slots` are not. Code using decorator mapping gets the same result from `registry.mapped_as_dataclass` or the `mapped_as_dataclass()` function. Per attribute, `mapped_column()` takes the field options: `init`, `default`, `default_factory`, `repr`, `compare`, `kw_only` and `hash`. ## What breaks first A plain declarative class has a keyword-only constructor that accepts any mapped attribute. The dataclass constructor is stricter, and the first things to break are calls and class definitions: 1. **Parameters follow field order and may be positional.** `Account("[email protected]")` now works, and fields without a default are **required**. 2. **A database-generated primary key needs `init=False`.** Without it, `id` becomes a required argument and `Account(email=...)` raises `TypeError` for the missing `id`. 3. **Field order is enforced.** A field without a default declared after one with a default makes class creation fail with `InvalidRequestError: Python dataclasses error encountered when creating dataclass for 'Account'`, wrapping the dataclass `TypeError`. Reorder the fields, or pass `kw_only=True` on the base or the field. 4. **Defaults go through the ORM construct.** Write `mapped_column(default=None)` or `default_factory=list`; field options placed inside an `Annotated` template are ignored with a deprecation warning. 5. **Plain mixins stop working.** A mixin that declares mapped attributes but is not itself a dataclass makes 2.1 raise `InvalidRequestError`, beginning `When transforming <class '...Account'> to a dataclass, attribute(s) 'created_at' originates from superclass <class '...TimestampMixin'>, which is not a dataclass.` 2.0 only emitted a deprecation warning. The fix is `class TimestampMixin(MappedAsDataclass)`, or the `unmapped_dataclass` decorator when classes are mapped with decorators. ## Where defaults live in SQLAlchemy 2.1 2.1 changed how dataclass defaults reach the object. The generated `__init__()` uses a sentinel, `DONT_SET`, as the default for each defaulted parameter, and an argument left at that sentinel is **not stored in `__dict__`**. The `default=` value is delivered by the attribute **descriptor** whenever the attribute is read, and it is still the column's `Column.default`, so the INSERT sends it. | Declaration | In `__init__()` | `__dict__` after `__init__()` | At INSERT | |---|---|---|---| | `mapped_column(default="active")` | optional | no key; reading gives `"active"` | `'active'` sent | | `mapped_column(default_factory=list, type_=JSON)` | optional | factory result stored | stored value sent | | `mapped_column(insert_default=func.now(), init=False)` | absent | no key; reading gives `None` | `func.now()` rendered | | `mapped_column(server_default=func.now(), init=False)` | absent | no key; reading gives `None` | the database fills it | The practical effect: code that reads **`vars(obj)`** or `obj.__dict__`, such as a hand-written serialiser, no longer sees unpassed defaults until the flush loads them, while `getattr()`, `dataclasses.asdict()` and normal attribute access do. In 2.0 the generated `__init__()` wrote those defaults into `__dict__`, which also made a defaulted `None` many-to-one reference win over a foreign key value set in the same call. In 2.1, `default=` and `insert_default=` are also mutually exclusive, so a database-side value is declared with `insert_default=` (or `server_default=`) plus `init=False`. ## Equality, hashing and repr The generated `__eq__()` compares field values, and with the default `eq=True` the dataclass machinery sets `__hash__` to `None`. Two consequences: - two pending objects with the same field values compare **equal**, although they will become two rows; - instances become **unhashable**, so `{account}` or using an object as a dict key raises `TypeError`. Passing `eq=False` on the base, `class Base(MappedAsDataclass, DeclarativeBase, eq=False)`, keeps identity equality and hashing. The generated `__repr__()` reads every field with `repr=True`; marking collection or large text fields `repr=False` keeps logs readable and avoids loading attributes merely to print an object. ## A migration checklist - Make every mixin with mapped attributes subclass `MappedAsDataclass`. - Add `init=False` to generated keys and to server- or SQL-generated columns. - Order required fields before defaulted ones, or adopt `kw_only=True` across the base. - Move any field options out of `Annotated` templates into inline `mapped_column()` calls. - Replace `default=` plus `insert_default=` pairs with one of the two. - Search for `__dict__` and `vars()` readers and switch them to attribute access. - Decide on `eq=False` before any code puts mapped objects into sets.

  • Why does `account.status` read 'active' while `vars(account)` has no status key?
    In 2.1 the generated `__init__()` gives defaulted parameters the `DONT_SET` sentinel and stores nothing for an argument left at it. Reading the attribute goes through SQLAlchemy's descriptor, which returns the `default=` value for an unpopulated attribute. The same value is the column's `Column.default`, so the INSERT sends it, and after the flush it is in `__dict__`.
  • How do you keep mapped dataclass instances usable in sets and as dict keys?
    With the default `eq=True`, the generated `__eq__()` compares field values and `__hash__` is set to `None`, so instances are unhashable and two pending objects with equal fields compare equal. Declaring the base as `class Base(MappedAsDataclass, DeclarativeBase, eq=False)` keeps identity equality and hashing. `unsafe_hash=True` hashes field values, which change as attributes change.
  • Where should a database-generated `created_at` go on a mapped dataclass?
    Keep it out of the constructor and let SQL produce it: `mapped_column(insert_default=func.now(), init=False)` renders the function into the INSERT, while `mapped_column(server_default=func.now(), init=False)` leaves it to the table's DDL default. Do not add `default=` as well; in 2.1 it is mutually exclusive with `insert_default=`. The attribute reads `None` until the flush.

  • In SQLAlchemy 2.1 the generated __init__() writes each default into __dict__
  • A generated primary key needs no init=False because SQLAlchemy fills it in
  • MappedAsDataclass supports frozen=True for immutable mapped objects
  • Existing plain mixins keep working unchanged once the base adds MappedAsDataclass
  • init=False inside an Annotated alias keeps the field out of __init__()
  • Mapped dataclass instances still hash by identity like plain mapped objects

Assumes SQLAlchemy 2.1, where default= values reach mapped dataclass attributes through the descriptor instead of __dict__, and a plain mixin with mapped attributes raises instead of 2.0's deprecation warning.