Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python "or" operator weird behavior

First, the code:

>>> False or 'hello'
'hello'

This surprising behavior lets you check if x is not None and check the value of x in one line:

>>> x = 10 if randint(0,2) == 1 else None
>>> (x or 0) > 0
# depend on x value...

Explanation: or functions like this:

if x is false, then y, else x

No language that I know lets you do this. So, why does Python?

like image 697
mclafee Avatar asked Dec 13 '12 23:12

mclafee


People also ask

What does &= mean in Python?

It means bitwise AND operation. Example : x = 5 x &= 3 #which is similar to x = x & 3 print(x)

Is there an and/or operator in Python?

There are three Boolean operators in Python: and , or , and not . With them, you can test conditions and decide which execution path your programs will take.

Does Python have a === operator?

The == operator compares the value or equality of two objects, whereas the Python is operator checks whether two variables point to the same object in memory. In the vast majority of cases, this means you should use the equality operators == and != , except when you're comparing to None .

What does * Operator do Python list?

Python List also includes the * operator, which allows you to create a new list with the elements repeated the specified number of times.


2 Answers

It sounds like you're combining two issues into one.

First, there's the issue of short-circuiting. Marcin's answer addresses this issue perfectly, so I won't try to do any better.

Second, there's or and and returning the last-evaluated value, rather than converting it to bool. There are arguments to be made both ways, and you can find many languages on either side of the divide.

Returning the last-evaluated value allows the functionCall(x) or defaultValue shortcut, avoids a possibly wasteful conversion (why convert an int 2 into a bool 1 if the only thing you're going to do with it is check whether it's non-zero?), and is generally easier to explain. So, for various combinations of these reasons, languages like C, Lisp, Javascript, Lua, Perl, Ruby, and VB all do things this way, and so does Python.

Always returning a boolean value from an operator helps to catch some errors (especially in languages where the logical operators and the bitwise operators are easy to confuse), and it allows you to design a language where boolean checks are strictly-typed checks for true instead of just checks for nonzero, it makes the type of the operator easier to write out, and it avoids having to deal with conversion for cases where the two operands are different types (see the ?: operator in C-family languages). So, for various combinations of these reasons, languages like C++, Fortran, Smalltalk, and Haskell all do things this way.


In your question (if I understand it correctly), you're using this feature to be able to write something like:

if (x or 0) < 1:

When x could easily be None. This particular use case isn't very useful, both because the more-explicit x if x else 0 (in Python 2.5 and later) is just as easy to write and probably easier to understand (at least Guido thinks so), but also because None < 1 is the same as 0 < 1 anyway (at least in Python 2.x, so you've always got at least one of the two options)… But there are similar examples where it is useful. Compare these two:

return launchMissiles() or -1

return launchMissiles() if launchMissiles() else -1

The second one will waste a lot of missiles blowing up your enemies in Antarctica twice instead of once.


If you're curious why Python does it this way:

Back in the 1.x days, there was no bool type. You've got falsy values like None, 0, [], (), "", etc., and everything else is true, so who needs explicit False and True? Returning 1 from or would have been silly, because 1 is no more true than [1, 2, 3] or "dsfsdf". By the time bool was added (gradually over two 2.x versions, IIRC), the current logic was already solidly embedded in the language, and changing would have broken a lot of code.

So, why didn't they change it in 3.0? Many Python users, including BDFL Guido, would suggest that you shouldn't use or in this case (at the very least because it's a violation of "TOOWTDI"); you should instead store the result of the expression in a variable, e.g.:

missiles = launchMissiles()
return missiles if missiles else -1

And in fact, Guido has stated that he'd like to ban launchMissiles() or -1, and that's part of the reason he eventually accepted the ternary if-else expression that he'd rejected many times before. But many others disagree, and Guido is a benevolent DFL. Also, making or work the way you'd expect everywhere else, while refusing to do what you want (but Guido doesn't want you to want) here, would actually be pretty complicated.


So, Python will probably always be on the same side as C, Perl, and Lisp here, instead of the same side as Java, Smalltalk, and Haskell.

like image 131
abarnert Avatar answered Oct 27 '22 12:10

abarnert


No language that i know lets you do this. So, why Python do?

Then you don't know many languages. I can't think of one language that I do know that does not exhibit this "shortcircuiting" behaviour.

It does it because it is useful to say:

a = b or K

such that a either becomes b, if b is not None (or otherwise falsy), and if not it gets the default value K.

like image 34
Marcin Avatar answered Oct 27 '22 13:10

Marcin