This issue tracker has been migrated to GitHub, and is currently read-only.
For more information, see the GitHub FAQs in the Python's Developer Guide.

Author abrosimov.a.a
Recipients abrosimov.a.a
Date 2020-12-25.16:32:43
SpamBayes Score -1.0
Marked as misclassified Yes
Message-id <1608913963.27.0.877253757924.issue42742@roundup.psfhosted.org>
In-reply-to
Content
I want to add `abc.Mapping` extension to `dataclasses.dataclass`.

Motivation:

1. `asdict` makes a deep copy of the `dataclass` object. If I only want to iterate over the `field` attributes, I don't want to do a deep copy.
2. `dict(my_dataclass)` can be used as a `dict` representation of `my_dataclass` class without deep copying.
3. `myfunc(**my_dataclass)` looks better and is faster then `myfunc(**asdict(my_dataclass))`.
4. `len(my_dataclass) == len(asdict(my_dataclass))` is expected behavior.
5. `my_dataclass.my_field is my_dataclass['my_field']` is expected behavior.


Looks like a prototype:

from collections.abc import Mapping
from dataclasses import dataclass, fields, _FIELDS, _FIELD


@dataclass  # `(mapping=True)` creates such a class:
class MyDataclass(Mapping):
    a: int = 1
    b: int = 2

    # In `dataclasses._process_class`:
    # if `mapping` is `True`.
    # Make sure 'get', 'items', 'keys', 'values' is not in `MyDataclass` fields.

    def __iter__(self):
        return (f.name for f in fields(self))

    def __getitem__(self, key):
        fields = getattr(self, _FIELDS)
        f = fields[key]
        if f._field_type is not _FIELD:
            raise KeyError(f"'{key}' is not a field of the dataclass.")
        return getattr(self, f.name)

    def __len__(self):
        return len(fields(self))


my_dataclass = MyDataclass(b=3)
print(my_dataclass['a'])
print(my_dataclass['b'])
print(dict(my_dataclass))
print(dict(**my_dataclass))

Stdout:
1
3
{'a': 1, 'b': 3}
{'a': 1, 'b': 3}


Realisation:

Updating the `dataclasses.py`: `dataclass`, `_process_class`, `_DataclassParams`.
Set `mapping` argument to default `False`.


Can this enhancement be accepted?
History
Date User Action Args
2020-12-25 16:32:43abrosimov.a.asetrecipients: + abrosimov.a.a
2020-12-25 16:32:43abrosimov.a.asetmessageid: <1608913963.27.0.877253757924.issue42742@roundup.psfhosted.org>
2020-12-25 16:32:43abrosimov.a.alinkissue42742 messages
2020-12-25 16:32:43abrosimov.a.acreate