var or inout parm?

Hrvoje Niksic hniksic at xemacs.org
Fri Dec 12 14:34:17 CET 2008


sturlamolden <sturlamolden at yahoo.no> writes:

> On Dec 12, 1:44 pm, "Chris Rebert" <c... at rebertia.com> wrote:
>
>> Python begs to differ, as those two statements are both semantically
>> identical in this case:
>
> That is because integers are immutable. When x += 1 is done on an int,
> there will be a rebinding. But try the same on say, a numpy array, and
> the result will be different:

The result will be different, but a still occurs!  You usually don't
notice it because augmented assignments with side effect are normally
careful to return the same object, so rebinding is a no-op.  But in
some cases, that can byte you.  For example, tupleobj[0] += 1 raises
an exception even when tupleobj[0] is mutable.  Taking the numpy
example:

>>> 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.])



More information about the Python-list mailing list