new python 3.6 ,we can use a class definition with typing.NamedTuple
to create a namedtuple:
from typing import NamedTuple class ANamedTuple(NamedTuple): """a docstring""" foo: int bar: str baz: list
The above is the same as the below, except the above additionally has type annotations and a docstring. The below is available in Python 2+:
>>> from collections import namedtuple
>>> class_name = 'ANamedTuple'
>>> fields = 'foo bar baz'
>>> ANamedTuple = namedtuple(class_name, fields)
This instantiates it:
>>> ant = ANamedTuple(1, 'bar', [])
We can inspect it and use its attributes:
>>> ant
ANamedTuple(foo=1, bar='bar', baz=[])
>>> ant.foo
1
>>> ant.bar
'bar'
>>> ant.baz.append('anything')
>>> ant.baz
['anything']