[issue24931] _asdict breaks when inheriting from a namedtuple

Raymond Hettinger report at bugs.python.org
Tue Aug 25 04:54:32 CEST 2015


Raymond Hettinger added the comment:

For __dict__, I'm not sure what the right behavior should by for subclasses that don't define __slots__.  In Python 3, the __dict__ is returning the dict for the subclass.  This might be the correct and most desirable behavior:

    >>> class Point(namedtuple('_Point', ['x', 'y'])):
            pass
    >>> a = Point(3, 4)
    >>> a.w = 5
    >>> a.__dict__
    {'w': 5}

If we leave the __dict__ behavior as is in Py3, then we still need to get _asdict() back to its documented behavior.  For that, we would need to disconnect it from __dict__ by restoring the Py2.7 code for _asdict():

    def _asdict(self):
        'Return a new OrderedDict which maps field names to their values'
        return OrderedDict(zip(self._fields, self))

All this needs to be thought-out carefully.  Putting in __dict__ support originally looked like a bugfix to get vars() working correctly, but it caused problems with pickling which then led to the addition of __getnewargs__.  It seems that defining __dict__ leads to problems no matter how you do it.

My inclination is to remove __dict__ and __getewargs__ from the namedtuple definition entirely and return to a simpler state of affairs that is easier to reason about and less likely to lead to unexpected behaviors like the one in this bug report.

One note:  using the Py2.7 namedtuple code in Python3 still doesn't restore the old behavior.  Something else in the language appears to have changed (causing the subclasses' __dict__ to take precedence over the inherited __dict__ property).

----------
priority: normal -> high
versions: +Python 3.5, Python 3.6

_______________________________________
Python tracker <report at bugs.python.org>
<http://bugs.python.org/issue24931>
_______________________________________


More information about the Python-bugs-list mailing list