Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
303 views
in Technique[技术] by (71.8m points)

decimal - 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.)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...