Kamyar
Kamyar

Reputation: 2694

How to make a TypeVar (Generic) type in python with dataclass constraint?

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

Answers (1)

intgr
intgr

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)

(source: typeshed)

Upvotes: 2

Related Questions