Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How are Python in-place operator functions different than the standard operator functions?

From the docs:

Many operations have an “in-place” version. The following functions provide a more primitive access to in-place operators than the usual syntax does; for example, the statement x += y is equivalent to x = operator.iadd(x, y). Another way to put it is to say that z = operator.iadd(x, y) is equivalent to the compound statement z = x; z += y.

Questions:

  • Why isn't operator.iadd(x, y) equivalent to z = x; z += y?

  • How does operator.iadd(x, y) differ from operator.add(x, y)?

Related question, but I'm not interested in Python class methods; just regular operators on built-in Python types.

like image 691
Leftium Avatar asked Jan 23 '11 08:01

Leftium


People also ask

What is the difference between the operator and the operator in Python?

Difference between == and is operators in PythonThe == operator helps us compare the equality of objects. The is operator helps us check whether different variables point towards a similar object in the memory. We use the == operator in Python when the values of both the operands are very much equal.

What is in place operator in Python?

Definition - In-place operation is an operation that changes directly the content of a given linear algebra, vector, matrices(Tensor) without making a copy. The operators which helps to do the operation is called in-place operator.

What are standard operators?

Standard operating procedure means a formal written procedure offi- cially adopted by the plant owner or operator and available on a routine basis to those persons responsible for carrying out the procedure.


1 Answers

First, you need to understand the difference between __add__ and __iadd__.

An object's __add__ method is regular addition: it takes two parameters, returns their sum, and doesn't modify either parameter.

An object's __iadd__ method also takes two parameters, but makes the change in-place, modifying the contents of the first parameter. Because this requires object mutation, immutable types (like the standard number types) shouldn't have an __iadd__ method.

a + b uses __add__. a += b uses __iadd__ if it exists; if it doesn't, it emulates it via __add__, as in tmp = a + b; a = tmp. operator.add and operator.iadd differ in the same way.

To the other question: operator.iadd(x, y) isn't equivalent to z = x; z += y, because if no __iadd__ exists __add__ will be used instead. You need to assign the value to ensure that the result is stored in both cases: x = operator.iadd(x, y).

You can see this yourself easily enough:

import operator
a = 1
operator.iadd(a, 2)
# a is still 1, because ints don't have __iadd__; iadd returned 3

b = ['a']
operator.iadd(b, ['b'])
# lists do have __iadd__, so b is now ['a', 'b']
like image 130
Glenn Maynard Avatar answered Oct 07 '22 19:10

Glenn Maynard