0

I do not understand the following behavior of nested named tuples in Python (3.6):

class Small(NamedTuple):
   item: float = 0.0

class Outer(NamedTuple):
   zz = Small(item=random())

When I create two instances of the Small tuple:

a = Small()
b = Small()
print(a is b)
print(a, b)

they are distinct as I expect

False
Small(item=0.0) Small(item=0.0)

However, when I create two instances of the Outer tuple

a = Outer()
b = Outer()
print(a is b)
print(a.zz is b.zz)
print(a.zz, b.zz)

they will share the zz field:

False
True
Small(item=0.9892612860711646) Small(item=0.9892612860711646)

Why? How can I prevent it? (If I used a list instead of a float, and added an element to one instance, it would obviously be in both of them)

Jirka
  • 4,184
  • 30
  • 40
  • 1
    If you don't want the `Small` instances shared, why use class variables? You need to use instance variables instead. – Christian Dean Aug 30 '17 at 20:55
  • Python != Java... You should read some tutorials on writing class definitions in Python, it does not work the same way as Java. So, the real question is, *why did you expect these two class variables to be different*? – juanpa.arrivillaga Aug 30 '17 at 21:02
  • @ChristianDean Thanks. I had no idea that tuple fields behave as class variables, I thought they were a concise way of creating instance variables. – Jirka Aug 30 '17 at 21:11
  • @Jirka what? It has nothing to do with the fact that you are working with tuples, it's the *syntax you are using*. They will be class variables, no matter the type you use. Again, Python != Java. – juanpa.arrivillaga Sep 01 '17 at 16:25

0 Answers0