7

In operators module we have a helper method operator.abs. But in python abs is already a function, and the only way I know to invoke the __abs__ method on an object is by function call anyway.

Is there some other fancy way I don't know about to take the absolute value of a number? If not, why does operator.abs exist in the first place, and what is an example where you would have to use it instead of plain old abs?

Charles
  • 50,943
  • 13
  • 104
  • 142
wim
  • 338,267
  • 99
  • 616
  • 750

1 Answers1

2

abs(...)
    abs(a) -- Same as abs(a).

No, I don’t think there’s some other fancy way you don’t know about, or really any reason at all for this to be here at all except for consistency (since operator has methods for the other __operator__s).

Ry-
  • 218,210
  • 55
  • 464
  • 476
  • But by that logic we should have, say, `operator.__hex__` and many others too. This seems to be the _only_ one in there which is already a function. – wim Mar 13 '14 at 18:08
  • @wim: Is a method called `__hex__` used by `hex()`? – Ry- Mar 13 '14 at 18:09
  • 1
    @wim: It uses `__index__` in Python 3, and `operator.index` exists. – Ry- Mar 13 '14 at 18:13
  • 1
    @wim: touche, there is a `__hex__` method. Then file an issue and ask why `hex` is not added but `abs` is. They'll tell you it is gone in Python 3 however. – Martijn Pieters Mar 13 '14 at 18:13
  • Well, there are many examples I could pick.. `__hash__` is another one you always get but there's no `operator.hash` – wim Mar 13 '14 at 18:16
  • 1
    @wim: Touché indeed! My next best guess would be that absolute value is a (common) mathematical operator, but hashing isn’t – it’s pretty much strictly a computer thing. – Ry- Mar 13 '14 at 18:17
  • Was there ever in very early python some now-deprecated operator for `abs(x)`, like `|x|` say? – wim Mar 13 '14 at 18:18
  • 1
    @wim: I don't think so, and anyway the `operator` module was introduced in 1.5, while the `abs` builtin function already existed before that. – RemcoGerlich Mar 13 '14 at 18:25
  • The [source](https://hg.python.org/cpython/file/7255af1a1c50/Lib/operator.py) is bizarre. They do `from bultins import abs as _abs` and then they do `def abs(a): return _abs(a)` ... ok then ... – wim May 25 '15 at 11:54
  • @wim: That’s to be able to have a docstring. – Ry- May 25 '15 at 15:03