Python: Why is embedded tuple shared

47 Views Asked by At

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)

0

There are 0 best solutions below