in place functions from operator module

Steven D'Aprano steve at REMOVE-THIS-cybersource.com.au
Sun Aug 29 20:12:30 EDT 2010


On Sun, 29 Aug 2010 07:44:47 -0700, ernest wrote:

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


The point is that if you could modify the int 4 to become 7, you would 
then see horrible things like this:


>>> a = 4
>>> operator.iadd(a, 3)
>>> 4 + 1  # the int "4" has been changed to have the value 7
8

Nobody wants that. Some very early versions of Fortran allowed that sort 
of thing, apparently by accident. I've been told you can get it to work 
with Lisp too, and Python with ctypes. You don't want to go there.

That is why ints are immutable in Python, and so "in-place" operations 
aren't really in-place for them.

Remember that 4 is an actual *object*, and so the iadd function can only 
see the object, not the name it is bound to. It sees 4 as the first 
argument, not the memory location of "a". There's no way for it to know 
which name you are trying to modify, or even if the object 4 is bound to 
any name.


-- 
Steven



More information about the Python-list mailing list