Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between add and iadd?

I'm not understanding the purpose of the in-place operators like iadd, imul, etc.

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.

It seems like I can always use either the in-place or regular operator interchangeably. Is one better than the other?

like image 873
Kevin Avatar asked Sep 09 '16 01:09

Kevin


1 Answers

The "in-place" functions for immutable objects cannot be implemented using an in-place algorithm, while for mutable objects they could be. The simple truth is that immutable objects don't change.

Otherwise, usage of "in-place" versus not "in-place" functions has deep ramifications when considering mutable objects. Consider the following:

>>> A = [1,2,3]
>>> B = A
>>> id(A)
4383125944
>>> id(B)
4383125944
>>> A = A + [1]
>>> id(A)
4383126376
>>> A += [1]
>>> id(A)
4383126376

Suppose you are writing some code where it is assumed that B is a soft copy of A (a mutable object). By not using the "in-place" function when modifying A, desired modifications to B can be quietly missed. What makes matters worse, is that quick visual inspection of the code makes it seem that the code (e.g., A = A + [2]) is implemented correctly (maybe it makes sense mathematically). If one really wants to just modify an object and not receive a new object, then the "in-place" function is the right way to go.

Neither is better than the other. Rather there are specific circumstances under which one might be preferred over the other.

like image 184
Robert Prévost Avatar answered Oct 22 '22 17:10

Robert Prévost