pythonabstract-syntax-treeunary-operator

What does `return +/- ` do in python?


I was going through the CPython source code and I found the following piece of code from the standard library(ast.py).

if isinstance(node.op, UAdd):
   return + operand
else:
   return - operand

I tried the following in my python interpreter

>>> def s():
...     return + 1
...
>>> s()
1

But this is same as the following right?

def s():
    return 1

Can any one help me to understand what does the expression return + or return - do in python and when we should use this?


Solution

  • plus and minus in this context are unary operators. That is, they accept a single operand. This is in comparison to the binary operator * (for example) that operates on two operands. Evidently +1 is just 1. So the unary operator + in your return statement is redundant.