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, eric.smith
Date 2020-12-25.21:23:55
SpamBayes Score -1.0
Marked as misclassified Yes
Message-id <1608931436.16.0.784836766064.issue42742@roundup.psfhosted.org>
In-reply-to
Content
An alternative way:

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

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

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

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


@dataclass
class MyDataclass(DataclassMappingMixin):
    a: int = 1
    b: int = 2


my_dataclass = MyDataclass(a='3')
print(my_dataclass.__class__.__mro__)
print(my_dataclass.__class__.__name__)
print(my_dataclass['a'])
print(my_dataclass['b'])
print(dict(my_dataclass))
print(dict(**my_dataclass))
print(fields(my_dataclass))


Result:
(<class '__main__.MyDataclass'>,
 <class '__main__.DataclassMappingMixin'>,
 <class 'collections.abc.Mapping'>,
 <class 'collections.abc.Collection'>,
 <class 'collections.abc.Sized'>,
 <class 'collections.abc.Iterable'>,
 <class 'collections.abc.Container'>,
 <class 'object'>)
MyDataclass
3
2
{'a': '3', 'b': 2}
{'a': '3', 'b': 2}
(Field(name='a',type=<class 'int'>, ...),
 Field(name='b',type=<class 'int'>, ...))
History
Date User Action Args
2020-12-25 21:23:56abrosimov.a.asetrecipients: + abrosimov.a.a, eric.smith
2020-12-25 21:23:56abrosimov.a.asetmessageid: <1608931436.16.0.784836766064.issue42742@roundup.psfhosted.org>
2020-12-25 21:23:56abrosimov.a.alinkissue42742 messages
2020-12-25 21:23:55abrosimov.a.acreate