Python syntax for namedtuple inside a namedtuple

Yannis picture Yannis · Apr 3, 2016 · Viewed 8.4k times · Source

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?

Answer

Łukasz Rogalski picture Łukasz Rogalski · Apr 3, 2016

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