Joel Vroom
Joel Vroom

Reputation: 1691

Mutable namedtuple?

Suppose I have:

from collections import namedtuple
NT = namedtuple('name', ['x'])

Can someone explain the difference between:

  1. NT.x = 3
  2. var = NT(x=3)

I can change NT.x to anything (mutable) but var.x is immutable. Why is that the case?

Upvotes: 1

Views: 993

Answers (3)

Thomas
Thomas

Reputation: 181745

NT.x is an attribute of the class NT, not of an instance of that class:

>>> NT.x
<property object at 0x7f2a2dac6e58>

Its presence is just telling you that instances of NT have a property called x. See also this question.

Upvotes: 2

timgeb
timgeb

Reputation: 78690

namedtuple is a class factory.

NT(x=3) gives you an instance of your freshly created class.

NT.x =3 sets an attribute on the class itself.

Upvotes: 2

user2357112
user2357112

Reputation: 280456

NT is not a namedtuple. NT is a class. Its instances are namedtuples.

You cannot reassign x on an instance. While you can technically mess with the x on the class, that will break attribute access for the x attribute of the instances, as the x on the class is a descriptor that instances rely on to implement the corresponding instance attribute.

Upvotes: 8

Related Questions