by jsmeaton · 12y ago · 0 comments
>But what if we put a mutable object into the immutable tuple? Well, modification works, but we also get a TypeError at the same time.
tup = ([],)
tup[0] += [1]
Of course that's an error. It's equivalent to: temp = tup[0]
temp += [1]
tup[0] = temp
But the given explanation is way too obtuse. This shouldn't be a mystery at all:> If we try to extend the list via += "then the statement executes STORE_SUBSCR, which calls the C function PyObject_SetItem, which checks if the object supports item assignment. In our case the object is a tuple, so PyObject_SetItem throws the TypeError. Mystery solved."
> For instance, to execute the statement x += y, where x is an instance of a class that has an __iadd__() method, x.__iadd__(y) is called.
However, this is patently not true, apparently:
tup = ([],)
tup[0].__iadd__([1]) # Works
print tup
tup = ([],)
tup[0] += [1] # TypeError
print tup
[1] https://docs.python.org/2/reference/datamodel.html#emulating...