"""Returns True if obj is an instance of a dataclass."""
returnhasattr(type(obj), _FIELDS)
defis_dataclass(obj):
"""Returns True if obj is a dataclass or an instance of a
dataclass."""
cls=objifisinstance(obj, type) elsetype(obj)
returnhasattr(cls, _FIELDS)
Pitch
Create a Dataclass(Protocol). Classes satisfying the Protocol should be compatible with dataclass methods such as dataclasses.astuple, dataclasses.asdict, dataclasses.fields and dataclasses.replace
It seems that currently the following is possible sufficient:
@runtime_checkableclassDataclass(Protocol):
r"""Protocol for dataclasses."""@propertydef__dataclass_fields__(self) ->Mapping[str, Field]:
r"""Return the fields of the dataclass."""
Remarks:
Additionally one might want to add a MutableDataclass, with __setattr__ and __delattr__.
As a side benefit, the dataclasses.is_dataclass can be equipped with a Typeguard for Dataclass-Protocol (issubclass(cls, Dataclass) currently won't work because only methods are checked)
The text was updated successfully, but these errors were encountered:
Feature or enhancement
Currently, the
dataclassesmodule only provides thedataclasses.is_dataclassfunction to check whether a class is in fact a dataclass.cpython/Lib/dataclasses.py
Lines 1258 to 1267 in 0a7936a
Pitch
Create a
Dataclass(Protocol). Classes satisfying the Protocol should be compatible with dataclass methods such asdataclasses.astuple,dataclasses.asdict,dataclasses.fieldsanddataclasses.replaceIt seems that currently the following is possible sufficient:
Remarks:
MutableDataclass, with__setattr__and__delattr__.dataclasses.is_dataclasscan be equipped with aTypeguardforDataclass-Protocol (issubclass(cls, Dataclass)currently won't work because only methods are checked)The text was updated successfully, but these errors were encountered: