Oin Oin - 5 months ago 38
Python Question

_asdict in Python 3 namedtuple subclass returns empty dictionary

How can I use

from a Python 3 subclass of

This is what I've tried:

class A(namedtuple('B', 'c')):

a = A(3)


This works fine in Python 2 and returns:

OrderedDict([('c', 3)])


Ok, this was listed as a bug in Issue 24931 and fixed in version 3.5.2 if I am not mistaken.

In my current version of Python 3.5.2 this performs as expected:

Out[7]: OrderedDict([('c', 3)])

In short, consider updating to 3.5.1+. If you cannot, implementing _asdict yourself, as is stated in a message on the issue tracker, seems like a viable alternative:

from collections import namedtuple, OrderedDict

class A(namedtuple('B', 'c')):
    def _asdict(self):
        return OrderedDict(zip(self._fields, self))