in place functions from operator module

Arnaud Delobelle arnodel at googlemail.com
Sun Aug 29 11:33:58 EDT 2010


ernest <nfdisco at gmail.com> writes:

> Hi,
>
> The operator module provides separate functions for
> "in place" operations, such as iadd(), isub(), etc.
> However, it appears that these functions don't really
> do the operation in place:
>
> In [34]: a = 4
>
> In [35]: operator.iadd(a, 3)
> Out[35]: 7
>
> In [36]: a
> Out[36]: 4
>
> So, what's the point? If you have to make the
> assignment yourself... I don't understand.
>
> Cheers,
> Ernest

That's because

   a += b

is executed as:

   a = a.__iadd__(b)

For immutable objects, (such as integers), a.__iadd__(b) returns a + b
*and then* this value is assigned to a (or rather 'a' is bound to the
value).  So for immutables objects, iadd(a, b) is the same as a + b

For mutable objects (such as lists), a.__iadd__(b) mutates the object
*and then* returns self so that when the assignement is executed, 'a'
will still be bound the the same object.  E.g. if a = [1, 2] then

    a += [3]

will first append 3 to the list and then reassign the list to 'a' (it is
unnecessary in this case but if this step was omitted, the "in place"
operators wouldn't work on immutables types).
   
-- 
Arnaud



More information about the Python-list mailing list