Reputation: 2694
Is there a way to constraint some TypeVar to be dataclass? for example something like:
A = TypeVar('A', dataclass) # Wrong code!
Upvotes: 4
Views: 871
Reputation: 20506
With modern mypy and pyright versions, it's possible to distinguish dataclasses from other classes.
The @dataclass
decorator adds a __dataclass_fields__
class attribute. A protocol can be defined that requires this attribute.
from dataclasses import Field
from typing import ClassVar, Any, Protocol
class DataclassInstance(Protocol):
__dataclass_fields__: ClassVar[dict[str, Field[Any]]]
T = TypeVar('T', bound=DataclassInstance)
Upvotes: 2