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 chrahunt
Recipients chrahunt
Date 2019-02-11.01:06:53
SpamBayes Score -1.0
Marked as misclassified Yes
Message-id <1549847214.14.0.863197964236.issue35960@roundup.psfhosted.org>
In-reply-to
Content
The metadata argument to dataclasses.field is not preserved in the resulting Field.metadata attribute if the argument is a mapping with length 0.

The docs for dataclasses.field state:

> metadata: This can be a mapping or None. None is treated as an empty dict. This value is wrapped in MappingProxyType() to make it read-only, and exposed on the Field object.

The docs for MappingProxyType() state:

> Read-only proxy of a mapping. It provides a dynamic view on the mapping’s entries, which means that when the mapping changes, the view reflects these changes.

I assumed that the mapping provided could be updated after class initialization and the changes would reflect in the field's metadata attribute. Indeed this is the case when the mapping is non-empty, but not when the mapping is initially empty.

For example:

    $ python
    Python 3.8.0a1+ (heads/master:9db56fb8fa, Feb 10 2019, 19:54:10)
    [GCC 7.3.0] on linux
    Type "help", "copyright", "credits" or "license" for more information.
    >>> from dataclasses import field
    >>> d = {}
    >>> v = field(metadata=d)
    >>> d['i'] = 1
    >>> v.metadata
    mappingproxy({})
    >>> v = field(metadata=d)
    >>> v.metadata
    mappingproxy({'i': 1})
    >>> d['j'] = 2
    >>> v.metadata
    mappingproxy({'i': 1, 'j': 2})

In my case I have a LazyDict into which I was trying to save partial(callback, field). I could not have the field before it was initialized so I tried:

    d = {}
    member: T = field(metadata=d)
    d['key'] = partial(callback, field)

and it failed same as above.

As a workaround, one can set a dummy value in the mapping prior to calling dataclasses.field and then remove/overwrite it afterwards.
History
Date User Action Args
2019-02-11 01:06:57chrahuntsetrecipients: + chrahunt
2019-02-11 01:06:54chrahuntsetmessageid: <1549847214.14.0.863197964236.issue35960@roundup.psfhosted.org>
2019-02-11 01:06:54chrahuntlinkissue35960 messages
2019-02-11 01:06:53chrahuntcreate