Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[dataclasses] [typing] Dataclass Protocol #102395

Open
randolf-scholz opened this issue Mar 3, 2023 · 0 comments
Open

[dataclasses] [typing] Dataclass Protocol #102395

randolf-scholz opened this issue Mar 3, 2023 · 0 comments
Labels
stdlib Python modules in the Lib dir type-feature A feature request or enhancement

Comments

@randolf-scholz
Copy link

randolf-scholz commented Mar 3, 2023

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)
@randolf-scholz randolf-scholz added the type-feature A feature request or enhancement label Mar 3, 2023
@arhadthedev arhadthedev added the stdlib Python modules in the Lib dir label Mar 4, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
stdlib Python modules in the Lib dir type-feature A feature request or enhancement
Projects
None yet
Development

No branches or pull requests

2 participants