Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does a plus sign do in front of a variable in Python?

There's the following bit of Python code in a project I have to maintain:

# If the `factor` decimal is given, compute new price and a delta
factor = +factor.quantize(TWOPLACES)
new_price = +Decimal(old_price * factor).quantize(TWOPLACES)
delta = new_price - old_price

The question here is the purpose of + in front of a variable.

Python docs call it unary plus operator, which “yields its numeric argument unchanged”. Can it be safely removed then?

(Incidentally, the code was written by me some time ago, hopefully I've learned the lesson—it wouldn't be a question if tests existed, or if the use of unary plus on a decimal was clarified in comments.)

like image 397
Anton Strogonoff Avatar asked May 25 '12 03:05

Anton Strogonoff


People also ask

What does the plus symbol do in Python?

A unary mathematical expression consists of only one component or element, and in Python the plus and minus signs can be used as a single element paired with a value to return the value's identity ( + ), or change the sign of the value ( - ). With a negative value the plus sign returns the same negative value.

What does =+ mean in Python?

In, Python += adds another value with the variable's value and assigns the new value to the variable.

What is the purpose of a plus symbol before a variable?

The plus(+) sign before the variables defines that the variable you are going to use is a number variable.

What is the difference between += and =+ in Python?

+ is an arithmetic operator while += is an assignment operator..


2 Answers

What that plus sign does depends on what it's defined to do by the result of that expression (that object's __pos__() method is called). In this case, it's a Decimal object, and the unary plus is equivalent to calling the plus() method. Basically, it's used to apply the current context (precision, rounding, etc.) without changing the sign of the number. Look for a setcontext() or localcontext() call elsewhere to see what the context is. For more information, see here.

The unary plus is not used very often, so it's not surprising this usage is unfamiliar. I think the decimal module is the only standard module that uses it.

like image 105
kindall Avatar answered Oct 19 '22 01:10

kindall


I ran into this same problem when I wrongly assumed that Python must support the C increment (++) operator; it doesn't! Instead, it applies the plus-sign operator (+) twice! Which does nothing twice, I soon learned. However, because "++n" looked valid... not flagged as a syntax error... I created a terrible bug for myself.

So unless you redefine what it does, unary + actually does nothing. Unary - changes from positive to negative and vice-versa, which is why "--n" is also not flagged as a syntax error but it also does nothing.

like image 27
Brian Overland Avatar answered Oct 19 '22 01:10

Brian Overland