Plain annotations for descriptor-backed fields (ORMs, dataclass_transform)

I agree that a general mechanism is the right long-term answer, and PEP 827’s motivation makes that case well. To see how close it gets here, I tried the PoC mypy fork (‘msullivan/mypy’, branch ‘typemap’, commit ‘5e9ae8d’). It can express the access typing, with ‘dataclass_transform’ still synthesizing ‘init’ (excerpt; the full probe is at the end):

type Descriptor[Type, Init] = (
    Type
    if IsAssignable[Type, Column[Any] | Relationship[Any]]
    else Relationship[Type]
    if IsAssignable[Literal["relationship"], GetMemberType[Init, Literal["kind"]]]
    else Column[Type]
)


class Model(metaclass=ModelMeta):  # ModelMeta still uses dataclass_transform
    def __init_subclass__[T](cls: type[T]) -> UpdateClass[
        *[
            Member[p.name, Descriptor[p.type, p.init], p.quals, p.init]
            for p in Iter[Attrs[T]]
            if not IsAssignable[Literal["ClassVar"], p.quals]
        ]
    ]: ...


class Parent(Model):
    memo: str | None = None
    children: list[Child] = relationship(default=[])
    registry: ClassVar[str] = "parents"


reveal_type(Parent.memo)              # Column[str | None]
reveal_type(Parent().memo)            # str | None
reveal_type(Parent.memo == "refund")  # Expression
reveal_type(Parent.children)          # Relationship[list[Child]]
reveal_type(Parent.registry)          # str
Parent(memo=1)                        # error: expected "str | None"

The descriptor is chosen per field, here from the specifier, so under PEP 827 the class-wide versus specifier question from my post goes away. Plain defaults are checked against the declared type, as rule 5 in my post asks (‘memo: str | None = 1’ is rejected).

The constructor is the open part. The PEP doesn’t say how ‘UpdateClass’ combines with ‘dataclass_transform’, and in the PoC ‘init’ uses the declared type while assignment goes through the updated descriptor. With a setter that also accepts SQL expressions (‘value: T | Expression’), ‘parent.memo = Parent.memo == “x”’ is accepted but ‘Parent(memo=Parent.memo == “x”)’ is rejected. When a field is annotated with the descriptor type, mypy 2.3.1, pyright 1.1.408 and ty 0.0.17 take the ‘init’ parameter from ‘set’ instead.

The alternative is to build ‘init’ in the same ‘UpdateClass’, as the PEP’s ‘Model’ example does. The PEP calls that example simplified (every parameter is keyword-only), and a full version would reimplement, as type-level code, the constructor rules that ‘dataclass_transform’ already provides. ‘KW_ONLY’ support, for one, needs a recursive type alias over the members, as noted in the PEP 827 thread.

That’s why I’d still like to discuss a narrow rule alongside PEP 827:

  • It reuses what checkers already do. Constructor synthesis (defaults, ‘kw_only’, ‘init=False’, aliases) stays with ‘dataclass_transform’, which mypy, pyright and ty already implement. ‘init’ takes the ‘set’ type, as it already does for descriptor-typed fields. The new work is typing a field as ‘Column[T]’ for access and assignment while checking a plain default against ‘T’.
  • It fits PEP 827. The ‘Descriptor’ alias above is a sketch of the class-wide rule in my post, so if PEP 827 lands, the narrow rule could be described as a transformation of that kind.
  • There’s a process for it. ‘converter’ was added to ‘dataclass_transform’ in 2024 by a Typing Council decision, after PEP 712 was rejected. It followed this discussion, which asked for a concrete spec change and, ideally, an implementation in at least one checker.

So, two open questions. Is combining ‘UpdateClass’ with ‘dataclass_transform’ meant to be supported, and should ‘init’ then follow the updated descriptor? And would a narrow ‘dataclass_transform’ rule for this be welcome in the meantime, or is it better to leave ‘dataclass_transform’ as it is while PEP 827 develops?

Full probe, plus a note on InitField (run with --python-version 3.15 on the PoC fork)

The PoC’s ‘InitField’ inherits from ‘Any’ (marked TODO in its stub), so ‘IsAssignable’ can’t tell ‘relationship(…)’ apart from no initializer (‘Never’). The ‘kind’ marker on ‘relationship’ works around that.

from typing import (
    Any, Attrs, BaseTypedDict, ClassVar, InitField, IsAssignable, GetMemberType, Iter, Literal, Member,
    NotRequired, Self, UpdateClass, dataclass_transform, overload, reveal_type,
)


class Expression: ...


class Column[T]:
    @overload
    def __get__(self, instance: None, owner: type[Any]) -> Self: ...
    @overload
    def __get__(self, instance: object, owner: type[Any]) -> T: ...
    def __get__(self, instance: object | None, owner: type[Any]) -> Self | T:
        raise NotImplementedError

    def __set__(self, instance: object, value: T | Expression) -> None: ...

    def __eq__(self, other: object) -> Expression:  # type: ignore[override]
        raise NotImplementedError


class Relationship[T]:
    @overload
    def __get__(self, instance: None, owner: type[Any]) -> Self: ...
    @overload
    def __get__(self, instance: object, owner: type[Any]) -> T: ...
    def __get__(self, instance: object | None, owner: type[Any]) -> Self | T:
        raise NotImplementedError

    def __set__(self, instance: object, value: T) -> None: ...


class RelationshipArgs(BaseTypedDict):
    default: NotRequired[Any]


class relationship[KwargDict: BaseTypedDict = RelationshipArgs](InitField[KwargDict]):
    kind: Literal["relationship"]


type Descriptor[Type, Init] = (
    Type
    if IsAssignable[Type, Column[Any] | Relationship[Any]]
    else Relationship[Type]
    if IsAssignable[Literal["relationship"], GetMemberType[Init, Literal["kind"]]]
    else Column[Type]
)


@dataclass_transform(kw_only_default=True, field_specifiers=(relationship,))
class ModelMeta(type): ...


class Model(metaclass=ModelMeta):
    def __init_subclass__[T](cls: type[T]) -> UpdateClass[
        *[
            Member[p.name, Descriptor[p.type, p.init], p.quals, p.init]
            for p in Iter[Attrs[T]]
            if not IsAssignable[Literal["ClassVar"], p.quals]
        ]
    ]:
        raise NotImplementedError


class Child(Model):
    name: str


class Parent(Model):
    memo: str | None = None
    children: list[Child] = relationship(default=[])
    registry: ClassVar[str] = "parents"


reveal_type(Parent.memo)  # Column[str | None]
reveal_type(Parent().memo)  # str | None
reveal_type(Parent.memo == "refund")  # Expression
reveal_type(Parent.children)  # Relationship[list[Child]]
reveal_type(Parent().children)  # list[Child]
reveal_type(Parent.registry)  # str
reveal_type(Child.name)  # Column[str]
Parent(memo=1)  # error: expected "str | None"
Parent(memo="ok", children=[Child(name="x")])
Parent(mmo="typo")  # error: unexpected keyword argument


class Explicit(Model):
    count: Column[int] = Column()


reveal_type(Explicit.count)  # Column[int]


class BadDefault(Model):
    memo: str | None = 1  # error: incompatible types in assignment


parent = Parent()
parent.memo = Parent.memo == "x"  # accepted: Column.__set__ takes T | Expression
Parent(memo=Parent.memo == "x")  # error: expected "str | None"