Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 739
Yannis Avatar asked Apr 03 '16 11:04

Yannis


People also ask

How do you input a Namedtuple in Python?

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.

What does Namedtuple return in Python?

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.

How do I change Namedtuple value?

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.

How do I change attributes in Namedtuple?

A Python namedtuple is Immutable. Like its regular counterpart, a python namedtuple is immutable. We can't change its attributes.


1 Answers

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
like image 182
Łukasz Rogalski Avatar answered Sep 20 '22 17:09

Łukasz Rogalski