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?
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')
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With