Search code examples
python-3.xcollectionsnamedtuple

How to retrieve the fields of a namedtuple class (not instance)?


Given a namedtuple:

from collections import namedtuple

MyNamedTuple = namedtuple('MyNamedTuple', ['foo','bar'])

I would like get an iterable over the fields of MyNamedTuple . Currently I do

[k for k in MyNamedTuple._fields]

but this uses the protected/private attribute _fields. Is there a way to do this without using _fields or a protected/private attribute/methods?


Solution

  • I would say _fields is the right class attribute to use, as that is its documented purpose.

    I don't know the reason they chose to prepend this attribute's name with an underscore, however.