Is it possible to have a namedtuple
inside another namedtuple
?
For example:
from collections import namedtuple
Position = namedtuple('Position', 'x y')
Token = namedtuple('Token', ['key', 'value', Position])
which gives a "ValueError: Type names and field names must be valid identifiers"
Also, I am curious if there is a more Pythonic approach to build such a nested container?
Python namedtuple basic example First, we import the namedtuple type from the collections module. We define the namedtuple. The first argument is the name for the namedtuple. The second argument are the field names.
The namedtuple is a function that returns a new named tuple class. In other words, the namedtuple() is a class factory. The namedtuple function accepts the following arguments to generate a class: A class name that specifies the name of the named tuple class.
Since a named tuple is a tuple, and tuples are immutable, it is impossible to change the value of a field. In this case, we have to use another private method _replace() to replace values of the field. The _replace() method will return a new named tuple.
A Python namedtuple is Immutable. Like its regular counterpart, a python namedtuple is immutable. We can't change its attributes.
You are mixing up two concepts - structure of namedtuple
, and values assigned to them. Structure requires list of unique names. Values may be anything, including another namedtuple
.
from collections import namedtuple
Position = namedtuple('Position', 'x y')
Token = namedtuple('Token', ['key', 'value', 'position'])
t = Token('ABC', 'DEF', Position(1, 2))
assert t.position.x == 1
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With