Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: what's the difference - abs and operator.abs

In python what is the difference between :

abs(a) and operator.abs(a)

They are the very same and they work alike. If they are the very same then why are two separate functions doing the same stuff are made??

If there is some specific functionality for any one of it - please do explain it.

like image 392
Gourab Avatar asked Dec 19 '22 17:12

Gourab


2 Answers

There is no difference. The documentation even says so:

>>> import operator
>>> print(operator.abs.__doc__)
abs(a) -- Same as abs(a).

It is implemented as a wrapper just so the documentation can be updated:

from builtins import abs as _abs

# ...

def abs(a):
    "Same as abs(a)."
    return _abs(a)

(Note, the above Python implementation is only used if the C module itself can't be loaded).

It is there purely to complement the other (mathematical) operators; e.g. if you wanted to do dynamic operator lookups on that module you don't have to special-case abs().

like image 179
Martijn Pieters Avatar answered Dec 21 '22 11:12

Martijn Pieters


No difference at all. You might wanna use operator.abs with functions like itertools.accumulate, just like you use operator.add for +. There is a performance differene though.

For example using operator.add is twice as fast as +(Beazly).

like image 39
C Panda Avatar answered Dec 21 '22 10:12

C Panda