r/learnpython • u/Bunslow • Oct 23 '26
In-place updates to objects count as tuple assignment?
Test case:
s = {1, 2, 3, 4}
grid = tuple(s.copy() for i in range(2))
print(f"{grid[1]=}")
one = grid[1]
one &= {2, 3}
print(f"{grid[1]=}")
grid[1] &= {2}
The output is as so:
grid[1]={1, 2, 3, 4}
grid[1]={2, 3}
Traceback (most recent call last):
File "/home/bill/bin/fivefold/test.py", line 7, in <module>
grid[1] &= {2}
~~~~^^^
TypeError: 'tuple' object does not support item assignment
Is it me or is this very surprising, a seeming violation of self-consistent behavior of Python? Simply renaming the reference to the object changes how I may or may not mutate the object. Clearly I'm not modifying the tuple, just deferencing the pointer to the contained object. version 3.11.2
0
Upvotes
View all comments
Show parent comment
0
u/Bunslow Oct 23 '26
hmm, i wonder how this came to be. is there a real reason or just a historical accident? obviously i kinda wish it was the other way, that the __iand__ grabbed the pointer before __setitem__ got anywhere near it, but i have no idea what the motivation may be for this either way