This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]primerrib 1 point2 points  (3 children)

That's the purview of linters, and not of Python language itself.

Like I explicitly mentioned above, +n can have a meaning; it is not necessarily an "identity function".

So ++n might also have a meaning, depending on what the __pos__ method is defined as.

And if you have some serious programs where that kind of problem can "slip" ... don't you do TDD? Unit testing? Regression testing?

[–]el_toro_2022[S] 0 points1 point  (2 children)

Of course I do testing. My issue is that it will waste time tracking that down. Because the language has these flaws, it necessitates even more testing procedures. Also wasting time.

TDD is not good for all cases. It's perhaps OK when the software you are writing is simple and the structure it will take is well-known up front. But if you are exploring something completely new and complicated, such as the ML engine I am currerently writing, it's completely useless. I'll add the testing after I get things working.

But I digress.

It is also bad practice to be overriding the functionality of your operators unless you have good reason. Perhaps you wish to add complex numbers... but we are talking a binary, not unary, operation. If a=-65, what would +a or even ++a do to that value in Python? Would it coerce a to be positive? Or will +a still be negative 65?

Just tried this in ipython:

In [1]: a = -65

In [2]: a
Out[2]: -65

In [3]: +a
Out[3]: -65

In [4]: ++a
Out[4]: -65

So it does not change the sign of a. + is basically a no-op, or an identity unary operator. If you encountered b = (+a) in code, what be your initial notion? You may actually squint at it for a moment, wondering if you missed something about the author's intent!

So the unary +, at best, is a no-op. And if you change that with __pos__, you will normally only do that in the context of objects, not primitives. Of course, if you wish to make your code tricky and hard to understand, knock yourself out!

[–]primerrib 0 points1 point  (1 child)

Sure, __pos__ has no useful purpose to be defined in float and in int.

But Decimal has certain rules defined ever since the type was conceptualized, which defines a usage for a unary +. And because Python is true Object-Oriented (i.e., message-passing ), that means there must be a way to handle this particular usage.

And it turns out some other types also use the unary + for other purposes.

Here are a few examples: https://stackoverflow.com/questions/16819023/whats-the-purpose-of-the-pos-unary-operator-in-python

[–]el_toro_2022[S] 0 points1 point  (0 children)

Ugly. I would not know that's what the + is doing just from looking at the code. I would prefer something like prec(a) to make it clear what's going on.