relative speed of incremention syntaxes (or "i=i+1" VS "i+=1")
Terry Reedy
tjreedy at udel.edu
Sun Aug 21 20:35:32 EDT 2011
On 8/21/2011 5:07 PM, Nobody wrote:
> If the value on the left has an __iadd__ method, that will be called;
Correct
> the value will be updated in-place,
Not necessarily correct. The target is rebound to the return from the
__iadd__ method. Augmented *assignment* is always assignment. This trips
up people who try
t = (1, [])
t[1] += [1,2] # which *does* extend the array, but raises
TypeError: 'tuple' object does not support item assignment
# instead of
t[1].extend([1,2]) # which extends without raising an error
*IF* (and only if) the target object is mutable, then the __iadd__ may
optionally mutate the target object. But the rebinding takes place
nonetheless. Numbers, the subject of this thread, are not mutable and
are not 'updated in-place'
class test:
def __init__(self, n):
self.n = n
def __iadd__(self, other):
return test(self.n + other.n)
def __repr__(self):
return repr(self.n)
r = test(1)
t = r
t += r
print(r, t)
# 1,2
That said, there is normally no reason to write an __ixxx__ method
unless instances are mutable and the operation can be and is done in
place therein. So the class above is for illustrative purposes only. A
saner example is the following, which treats test examples as mutable
number containers rather than as immutable surrogates.
class test:
def __init__(self, n):
self.n = n
def __add__(self, other):
return test(self.n + other.n)
def __iadd__(self, other):
n = self.n + other.n
self.n = n
return n
def __repr__(self):
return repr(self.n)
r = test(1)
t = r
t += r
print(r, t)
# 2 2
The interpreter cannot enforce that 'x += a' have the same effect as 'x
= x+a', but it would break normal expectations to make the two different.
> so all references to that object will be affected:
Only if the target object is mutable and is mutated by the optional
augmented assignment __ixxx__ methods.
> > import numpy as np
> > a = np.zeros(3)
Numpy arrays meet the qualification above.
> If the value on the left doesn't have an __iadd__ method, then addition is
> performed and the name is re-bound to the result:
As is also done with the results of __ixxx__ methods.
--
Terry Jan Reedy
More information about the Python-list
mailing list