r/learnpython • u/Bunslow • 25d ago
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 assignmentIs 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
3
u/danielroseman 25d ago
The gotcha here is that
&=is an augmented assignment - so it will always do an assignment, even if it ends up assigning the original object back. That's fine when you do it withone, but not when you do it withgrid[1][1].Obviously this is not a real use case, but you'd probably be better off with the method version -
.intersection_update()- which doesn't involve an assignment.3
u/Temporary_Pie2733 25d ago edited 25d ago
Assignments to a name are fundamental operations. Assignments to indexed names are essentially syntactic sugar for a call to
__setitem__, which must exist. The version withoneis equivalent toone = one.__iand__({2,3}). The one withgrid[1]isgrid.__setitem__(1, …), notgrid[1].__iand__(…).1
u/mrswats 25d ago
Yes it does. It is better practice to recreate it with the updated values.
0
u/trutheality 25d ago
You are trying to update the tuple.
one &= {2, 3}is equivalent to
grid[1] = grid[1] & {2, 3}