I am new to Python's namedtuple
, particularly, _field_defaults
.
According to Python 3.12.3 official doc,
some
namedtuple._field_defaults
Dictionary mapping field names to default values.
Would someone explain the odd behavior of the following code snippet? Apparently, the one provided by Copilot generates the error code listed below.
Text-based code snippet from above.
from collections import namedtuple
# Define the namedtuple
Person = namedtuple('Person', 'name age')
# Set default values
Person._field_defaults['name'] = 'John'
Person._field_defaults['age'] = 30
# Create a namedtuple with default values
person1 = Person()
# Create a namedtuple with a different name
person2 = Person(name='Alice')
print(person1) # Outputs: Person(name='John', age=30)
print(person2) # Outputs: Person(name='Alice', age=30)
The following error was produced.
>>> person1 = Person()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: <lambda>() missing 2 required positional arguments: 'name' and 'age'
>>> Person=namedtuple('Person', ['name', 'age'], defaults=['default_name', 0])
>>> p = Person()
>>> p
Person(name='default_name', age=0)
>>> p._field_defaults
{'name': 'default_name', 'age': 0}
>>> p._field_defaults['age'] = 100
>>> p = Person()
>>> p
Person(name='default_name', age=0)
>>>
Observed from the code snippet above, p._field_defaults['age'] = 100
changed the dictionary, but the default construction of Person
was not updated.
You'll find the implementation at collections.__init__.py
. namedtuple
creates new types. In the current implementation (3.13), defaults are actually a tuple on the type's __new__
method. _field_names
is informational only. This is because..., well, I don't know. Things that start with "_" are implementation details that could change at any time. The default
parameter was added in python 3.7 and its implementation may have changed over time. You really shouldn't depend on how it works on any given release (like the codepilot snippet did).
As for the order of defaults, the documentation states
Since fields with a default value must come after any fields without a default, the defaults are applied to the rightmost parameters.
This is how a python function is called, so namedtuple has to play the game.