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

Peter Stewart picture Peter Stewart · Jan 30, 2010 · Viewed 40.4k times · Source

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?

Answer

Lasse V. Karlsen picture Lasse V. Karlsen · Jan 30, 2010

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.