Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the purpose of the + (pos) unary operator in Python?

Tags:

python

Generally speaking, what should the unary + do in Python?

I'm asking because, so far, I have never seen a situation like this:

+obj != obj 

Where obj is a generic object implementing __pos__().

So I'm wondering: why do + and __pos__() exist? Can you provide a real-world example where the expression above evaluates to True?

like image 355
user16538 Avatar asked May 29 '13 16:05

user16538


People also ask

What is the use of unary operator in Python?

The – operator in Python can be utilized in a unary form. The unary structure implies character, restoring the same value as its operand. The unary structure implies negate, restoring the nullified incentive as its operand: zero to zero, positive to negative, and negative to positive.

What does POS mean in Python?

Parts of Speech (POS) Tagging. Parts of speech tagging simply refers to assigning parts of speech to individual words in a sentence, which means that, unlike phrase matching, which is performed at the sentence or multi-word level, parts of speech tagging is performed at the token level.

Why we are using unary operator?

We use this operator to increment the overall value of any given variable by a value of 1. We can perform increment using two major ways: Prefix increment.

What does the unary & operator do?

A unary operator is an operator used to operate on a single operand to return a new value. In other words, it is an operator that updates the value of an operand or expression's value by using the appropriate unary operators. In Unary Operator, operators have equal priority from right to left side associativity.


2 Answers

Here's a "real-world" example from the decimal package:

>>> from decimal import Decimal >>> obj = Decimal('3.1415926535897932384626433832795028841971') >>> +obj != obj  # The __pos__ function rounds back to normal precision True >>> obj Decimal('3.1415926535897932384626433832795028841971') >>> +obj Decimal('3.141592653589793238462643383') 
like image 50
Chris Taylor Avatar answered Oct 20 '22 05:10

Chris Taylor


In Python 3.3 and above, collections.Counter uses the + operator to remove non-positive counts.

>>> from collections import Counter >>> fruits = Counter({'apples': 0, 'pears': 4, 'oranges': -89}) >>> fruits Counter({'pears': 4, 'apples': 0, 'oranges': -89}) >>> +fruits Counter({'pears': 4}) 

So if you have negative or zero counts in a Counter, you have a situation where +obj != obj.

>>> obj = Counter({'a': 0}) >>> +obj != obj True 
like image 34
flornquake Avatar answered Oct 20 '22 04:10

flornquake