What's the purpose of the + (pos) unary operator in Python?

前端 未结 6 1543
日久生厌
日久生厌 2020-11-27 18:04

Generally speaking, what should the unary + do in Python?

I\'m asking because, so far, I have never seen a situation like this:

+obj !=          


        
6条回答
  •  春和景丽
    2020-11-27 19:02

    A lot of examples here look more like bugs. This one is actually a feature, though:

    The + 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.

提交回复
热议问题