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

PythonNamedtuple

Python Problem Overview


I was having trouble implementing namedtuple._replace(), so I copied the code right off of the documentation:

Point = namedtuple('Point', 'x,y')

p = Point(x=11, y=22)

p._replace(x=33)

print p

and I got:

Point(x=11, y=22)

instead of:

Point(x=33, y=22)

as is shown in the doc.

I'm using Python 2.6 on Windows 7

What's going on?

Python Solutions


Solution 1 - Python

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.

Solution 2 - Python

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

p = p._replace(x=33)

Solution 3 - Python

Solution 4 - Python

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.

Solution 5 - Python

But YES, you are right: in the 'official' documentation, they forgot to assign the replaced tuple to a variable: https://docs.python.org/3/library/collections.html?highlight=collections#collections.namedtuple

p._replace(x=33)

instead of

p1 = p._replace(x33)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionPeter StewartView Question on Stackoverflow
Solution 1 - PythonLasse V. KarlsenView Answer on Stackoverflow
Solution 2 - PythonMax ShawabkehView Answer on Stackoverflow
Solution 3 - PythonIgnacio Vazquez-AbramsView Answer on Stackoverflow
Solution 4 - PythonhughdbrownView Answer on Stackoverflow
Solution 5 - PythonAVPView Answer on Stackoverflow