Description
Feature or enhancement
Add the class dataclasses.Dataclass
that
- supports instance and subclass checks using similar logic as
dataclasses.is_dataclass
, and - blocks inheritance in
__init_subclass__
.
(Edit: removed "has an attribute __dataclass_fields__
for the purpose of type checking")
Pitch
This class would simplify runtime type-checking of dataclasses:
not isinstance(x, type) and dataclasses.is_dataclass(x) # Previously
isinstance(x, dataclasses.Dataclass) # With this feature.
and similarly
isinstance(x, type) and dataclasses.is_dataclass(x) # Previously.
issubclass(x, dataclasses.Dataclass) # With this feature.
Besides being simpler, it would also allow combined instance checks like isinstance(x, Dataclass | SomeOtherBase)
, which is arguably more Pythonic than the combined function calls above (marked "Previously").
It would also allow users to annotate dataclasses using Dataclass
or type[Dataclass]
, which is currently impossible without reaching into protected areas of the typeshed.
Inheritance could be blocked for now with a friendly error message (that perhaps tells you to use the decorator either directly or in a base class's __init_subclass__
).
Previous discussion
There's some discussion here: python/typing_extensions#115
@AlexWaygood
@JelleZijlstra
@henryiii