A function that confuses, does not do what it says it does

Viewed 61

In the operator module, there is a method that is called isub, which takes two parameters, and dividing the first parameter in the second one.

Visual Studio Code says it does this: Same as a -= b, How?

In my example, I'm creating a variable called a and assigning 5 as its value, and then using the isub method, and saving the result into a variable, and then printing the result and a, but a is still 5, why?

import operator

a = 5
result = operator.isub(a, 4)
print(result) # 1
print(a) # 5
1 Answers

You chose a poor example. int.__isub__ isn't defined, so a -= 5 is exactly equal to a = a - 5, with no in-place modification of the original value.

Try with a set, which does implement __isub__.

>>> s = {1,2,3}
>>> operator.isub(s, {2})
>>> s
{1, 3}

a -= b is implemented as a.__isub__(b) if a.__isub__ is defined. Otherwise, it is equivalent to a = a - b, which is implemented as a = a.__sub__(b). Thus, isub(a, b) is the same as a -= b, but that doesn't mean isub(a, b) can or does modify a in-place.

Related