Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does +Counter do in python? [duplicate]

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 804
user16538 Avatar asked Dec 01 '25 18:12

user16538


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 108
Chris Taylor Avatar answered Dec 03 '25 09:12

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 37
flornquake Avatar answered Dec 03 '25 10:12

flornquake



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!