Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How is it possible to evaluate +5 in Python?

How does evaluating + 5 work (spoiler alert: result is 5)?

Isn't the + working by calling the __add__ method on something? 5 would be "other" in:

>>> other = 5
>>> x = 1
>>> x.__add__(other)
6

So what is the "void" that allows adding 5?

void.__add__(5)

Another clue is that:

/ 5

throws the error:

TypeError: 'int' object is not callable
like image 744
PascalVKooten Avatar asked May 24 '15 10:05

PascalVKooten


2 Answers

The + in this case calls the unary magic method __pos__ rather than __add__:

>>> class A(int):
    def __pos__(self):
        print '__pos__ called'
        return self
...
>>> a = A(5)
>>> +a
__pos__ called
5
>>> +++a
__pos__ called
__pos__ called
__pos__ called
5

Python only supports 4(unary arithmetic operations) of them __neg__, __pos__, __abs__, and __invert__, hence the SyntaxError with /. Note that __abs__ works with a built-in function called abs(), i.e no operator for this unary operation.


Note that /5 (/ followed by something)is interpreted differently by IPython shell only, for normal shell it is a syntax error as expected:

Ashwinis-MacBook-Pro:py ashwini$ ipy
Python 2.7.6 (default, Sep  9 2014, 15:04:36)
Type "copyright", "credits" or "license" for more information.

IPython 3.0.0 -- An enhanced Interactive Python.
?         -> Introduction and overview of IPython's features.
%quickref -> Quick reference.
help      -> Python's own help system.
object?   -> Details about 'object', use 'object??' for extra details.
>>> /5
Traceback (most recent call last):
  File "<ipython-input-1-2b14d13c234b>", line 1, in <module>
    5()
TypeError: 'int' object is not callable

>>> /float 1
1.0
>>> /sum (1 2 3 4 5)
15

Ashwinis-MacBook-Pro:~ ashwini$ python
Python 2.7.6 (default, Sep  9 2014, 15:04:36)
[GCC 4.2.1 Compatible Apple LLVM 6.0 (clang-600.0.39)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> /5
  File "<stdin>", line 1
    /5
    ^
SyntaxError: invalid syntax
>>> /float 1
  File "<stdin>", line 1
    /float 1
    ^
SyntaxError: invalid syntax
like image 137
Ashwini Chaudhary Avatar answered Sep 18 '22 00:09

Ashwini Chaudhary


It looks like you've found one of the three unary operators:

  • The unary plus operation +x calls the __pos__() method.
  • The unary negation operation -x calls the __neg__() method.
  • The unary not (or invert) operation ~x calls the __invert__() method.
like image 42
Raymond Hettinger Avatar answered Sep 20 '22 00:09

Raymond Hettinger