Generally speaking, what should the unary +
do in Python?
I\'m asking because, so far, I have never seen a situation like this:
+obj !=
A lot of examples here look more like bugs. This one is actually a feature, though:
+
operator implies a copy.This is extremely useful when writing generic code for scalars and arrays.
For example:
def f(x, y):
z = +x
z += y
return z
This function works on both scalars and NumPy arrays without making extra copies and without changing the type of the object and without requiring any external dependencies!
If you used numpy.positive
or something like that, you would introduce a NumPy dependency, and you would force numbers to NumPy types, which can be undesired by the caller.
If you did z = x + y
, your result would no longer necessarily be the same type as x
. In many cases that's fine, but when it's not, it's not an option.
If you did z = --x
, you would create an unnecessary copy, which is slow.
If you did z = 1 * x
, you'd perform an unnecessary multiplication, which is also slow.
If you did copy.copy
... I guess that'd work, but it's pretty cumbersome.
Unary +
is a really great option for this.