1

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?

Delgan
  • 16,542
  • 9
  • 83
  • 127
Joel Vroom
  • 1,501
  • 1
  • 15
  • 29

3 Answers3

8

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.

user2357112
  • 235,058
  • 25
  • 372
  • 444
2

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.

timgeb
  • 73,231
  • 20
  • 109
  • 138
2

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.

Thomas
  • 162,537
  • 44
  • 333
  • 446