1

I am writing a function computing like eval. When I come to float.__pos__ ,I really don't Know why there exists such a useless function. Because:

>>> float.__pos__(-1.0)
-1.0
>>> float.__pos__(1.0)
1.0

while float.__neg__ is totally different:

>>> float.__neg__(1.0)
-1.0

So what is the meaning of float.__pos__?

tcpiper
  • 2,456
  • 2
  • 28
  • 41

3 Answers3

5
>>> help(float.__pos__)
Help on wrapper_descriptor:

__pos__(...)
    x.__pos__() <==> +x

It's the "unary plus" operator, invoked when you do +x with x a float. It basically does nothing for floats, as you've discovered ;-) However, you could define a subclass that did something non-trivial with it. That's why it's there.

Tim Peters
  • 67,464
  • 13
  • 126
  • 132
  • `a subclass that did something non-trivial with it`, something like what? I mean, what will happen if there is no __pos__ – tcpiper Nov 08 '13 at 02:48
  • thanks. I've saw the same question and known why. – tcpiper Nov 08 '13 at 02:57
  • @Pythoner, see the link @DavidGinsburg posted for examples of numeric types in Python where unary plus does do something non-trivial. If floats (or ints) didn't support `__pos__()`, the expression `+3.0` (or `+3`) would blow up at runtime, with an `AttributeError` *looking* for `__pos__` :-) – Tim Peters Nov 08 '13 at 02:58
3

The __pos__ method defines the effect of the unary + operator for any object.

As Tim Peters mentions, it has no effect for floats.

See What's the purpose of the + (pos) unary operator in Python? for an example where it's used to do something.

Community
  • 1
  • 1
1

Python has a unary negation operator to negate numbers, as you're probably well aware:

>>> x = 5
>>> print(-x)
-5
>>> x = -5
>>> print(-x)
5

Say you're making a list of numbers, though. It might be more consistent if you prefixed the positive ones with a +, so Python has a unary + operator, too:

>>> numbers = [-3, -2, -1, 0, +1, +2, +3]

When you use the unary + operator on a number, you're right that it doesn't do anything; it's there just for consistency.

Now when you consider that in Python you can override operators on types, of course you'd need a __neg__ to negate an instance of that type. Python just decided to be consistent by also having a __pos__ to…not negate an instance of that type. float, like all other types overriding these operators, follow this protocol, and float's implementation of __pos__ is just the identity function.

icktoofay
  • 126,289
  • 21
  • 250
  • 231