3

Today I noticed that the Python interpreter treats consecutive repetitions of the addition operator as just one repetition of the operator. For example:

>>> 1 ++ 2
3

Of what use was it to not simply raise an error when such an event occurs? I find it much more believable that a programmer who typed

>>> 1 -+-++ 2

was just out of their mind; it would be highly unlikely that this ever intentionally appears in code.

It seems to serve no purpose, for writing something like

>>> +-1

simply returns -1, demonstrating that the operation does not make the number positive, rather, it simply performs the identity operation.

wjandrea
  • 28,235
  • 9
  • 60
  • 81
R32415
  • 75
  • 7
  • ... `+(1) == 1` and `-(1) == -1` – Mateen Ulhaq Aug 04 '20 at 03:24
  • 2
    https://stackoverflow.com/q/16819023/1424875 may have some good discussion. One possible answer is that unary + and unary - are both defined for consistency/symmetry, and an added benefit is that unary + can be overridden where appropriate for certain classes. – nanofarad Aug 04 '20 at 03:25
  • 1
    Any excess operators found subsequently will be treated as [unary operator](https://docs.python.org/3/reference/expressions.html#unary-arithmetic-and-bitwise-operations) for the next value - there's actually one more, the inverse `~` operator, so the expression `-+~1` is also valid. They are backed by underlying operator methods [`__pos__`](https://docs.python.org/3/library/operator.html#operator.pos) for `+`, [`__neg__`](https://docs.python.org/3/library/operator.html#operator.__neg__) for `-`, and [`__invert__`](https://docs.python.org/3/library/operator.html#operator.__invert__) for `~`. – metatoaster Aug 04 '20 at 03:40

2 Answers2

1

Because it's overloaded. It's the addition operator (implemented by the __add__ method), and also the unary positive operator (implemented by __pos__). Compare that to -, which is the subtraction operator (__sub__) and unary negative operator (__neg__).

So for example, 1 ++ 2 is parsed as 1 + (+ 2) which simplifies down to 1 + 2 for integers, but not necessarily for other types. See What's the purpose of the + (pos) unary operator in Python?

wjandrea
  • 28,235
  • 9
  • 60
  • 81
0

It's mathematical. While it doesn't make sense to a normal person, to python +(+1) and -(-1) is +, +(-1) and -(+1) is -. Jumping back into the question, it isn't just python that does this. It's mathematical thinking. It's like telling a computer a variable called string is equal to 29. It sounds wrong but the computer thinks it is normal.

Z9.
  • 238
  • 2
  • 15