Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

namedtuple._replace() doesn't work as described in the documentation

Yes it does, it works exactly as documented.

._replace returns a new namedtuple, it does not modify the original, so you need to write this:

p = p._replace(x=33)

See here: somenamedtuple._replace(kwargs) for more information.


A tuple is immutable. _replace() returns a new tuple with your modifications:

p = p._replace(x=33)

namedtuple._replace() returns a new tuple; the original is unchanged.


It looks to me as if namedtuple is immutable, like its forebear, tuple.

>>> from collections import namedtuple
>>> Point = namedtuple('Point', 'x,y')
>>>
>>> p = Point(x=11, y=22)
>>>
>>> p._replace(x=33)
Point(x=33, y=22)
>>> print(p)
Point(x=11, y=22)
>>> p = p._replace(x=33)
>>> print(p)
Point(x=33, y=22)

NamedTuple._replace returns a new NamedTuple of the same type but with values changed.