views:

106

answers:

4

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 6.2 on Windows 7 edit: oops- that's Python 2.6

What's going on?

+2  A: 

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

Ignacio Vazquez-Abrams
Thank you all. I wish I could accept all the responses.
Peter Stewart
+2  A: 

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

p = p._replace(x=33)
Max Shawabkeh
+2  A: 

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.

Lasse V. Karlsen
+1  A: 

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)
hughdbrown