Skip to content

[dataclasses] [typing] Dataclass Protocol #102395

Closed as not planned
Closed as not planned
@randolf-scholz

Description

@randolf-scholz

Feature or enhancement

Currently, the dataclasses module only provides the dataclasses.is_dataclass function to check whether a class is in fact a dataclass.

cpython/Lib/dataclasses.py

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_dataclass can be equipped with a Typeguard for Dataclass-Protocol (issubclass(cls, Dataclass) currently won't work because only methods are checked)

Metadata

Metadata

Assignees

No one assigned

    Labels

    stdlibPython modules in the Lib dirtype-featureA feature request or enhancement

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions