You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
should mypy recognize pep-681 @dataclass_transform on a method as well as a function? #19824
Just noticed that trying to make an object method provide @dataclass_transform functionality is not recognized by mypy as a pep-681 use of @dataclass_transform (it does not complain either, just silently ignores it):
SQLAlchemy has a pep-681 feature that mostly uses the superclass approach, however we also offer a decorator that looks like @mapper_registry.mapped_as_dataclass(), and I just noticed that while pyright has always accepted this, mypy does not. So I'm adding an alternative decorator of the above form @mapped_as_dataclass(mapper_registry). Took a look at pep-681 and it discusses @dataclass_transform applied to a function or a class, not a method. So I'm out of luck. but it seems ....like it should work? pyright does it....
Funny enough, the typing spec does not mention methods either. I'm inclined to say that @dataclass_transform should be supported on methods (and it doesn't contradict PEP language, as methods are actually functions at the time when decorator is applied to then), but this is really somewhat grey area.
I have another usecase for that: Decorators that are implemented as a class using __call__ to do the decoration needs @dataclass_transform on methods (and in this case methods that are not "visible" on the call site) as well:
classdecorator:
@dataclass_transformdef__call__(self, cls):
returndataclass(cls)
@decorator()classDataclassLike:
i: int
In this case, instances of DataclassLike are not recognized as dataclasses by mypy.
Activity
sterliakov commentedon Sep 10, 2025
Funny enough, the typing spec does not mention methods either. I'm inclined to say that
@dataclass_transformshould be supported on methods (and it doesn't contradict PEP language, as methods are actually functions at the time when decorator is applied to then), but this is really somewhat grey area.tommie-lie commentedon Nov 9, 2025
I have another usecase for that: Decorators that are implemented as a class using
__call__to do the decoration needs@dataclass_transformon methods (and in this case methods that are not "visible" on the call site) as well:In this case, instances of DataclassLike are not recognized as dataclasses by mypy.