M
Marc 'BlackJack' Rintsch
import numpy
t = (numpy.zeros(10),)
t
(array([ 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.]),)>>> t[0] +=
1
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment
Of course, the side effect occurs before the exception, so:
t[0]array([ 1., 1., 1., 1., 1., 1., 1., 1., 1., 1.])
Actually I would consider this to be a bug. The tuple is immutable, but
no mutation of the tuple is ever attempted.
No bug because a mutation *is* attempted. ``a += x`` calls `a.__iadd__`
which *always* returns the result which is *always* rebound to the name
`a`. Even with mutable objects where `__iadd__()` simply returns
`self`! It has to be this way because the compiler has no idea if the
object bound to `a` will be mutable or immutable when the code actually
runs.
In [252]: def f(a, x):
.....: a += x
.....:
In [253]: dis.dis(f)
2 0 LOAD_FAST 0 (a)
3 LOAD_FAST 1 (x)
6 INPLACE_ADD
7 STORE_FAST 0 (a)
10 LOAD_CONST 0 (None)
13 RETURN_VALUE
Ciao,
Marc 'BlackJack' Rintsch