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
  • 18,571
  • 11
  • 90
  • 141
Joel Vroom
  • 1,611
  • 1
  • 16
  • 30

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
  • 260,549
  • 28
  • 431
  • 505
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
  • 76,762
  • 20
  • 123
  • 145
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
  • 174,939
  • 50
  • 355
  • 478