Search code examples
pythonpython-3.xnamedtuple

Python syntax for namedtuple inside a namedtuple


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?


Solution

  • 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