-
-
Notifications
You must be signed in to change notification settings - Fork 34.4k
[dataclasses] [typing] Dataclass Protocol #102395
Copy link
Copy link
Closed as not planned
Labels
stdlibStandard Library Python modules in the Lib/ directoryStandard Library Python modules in the Lib/ directorytype-featureA feature request or enhancementA feature request or enhancement
Description
Feature or enhancement
Currently, the dataclasses module only provides the dataclasses.is_dataclass function to check whether a class is in fact a dataclass.
Lines 1258 to 1267 in 0a7936a
| def _is_dataclass_instance(obj): | |
| """Returns True if obj is an instance of a dataclass.""" | |
| return hasattr(type(obj), _FIELDS) | |
| def is_dataclass(obj): | |
| """Returns True if obj is a dataclass or an instance of a | |
| dataclass.""" | |
| cls = obj if isinstance(obj, type) else type(obj) | |
| return hasattr(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_checkable
class Dataclass(Protocol):
r"""Protocol for dataclasses."""
@property
def __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_dataclasscan be equipped with aTypeguardforDataclass-Protocol (issubclass(cls, Dataclass)currently won't work because only methods are checked)
Reactions are currently unavailable
Metadata
Metadata
Assignees
Labels
stdlibStandard Library Python modules in the Lib/ directoryStandard Library Python modules in the Lib/ directorytype-featureA feature request or enhancementA feature request or enhancement