Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the purpose of "a and a or b"?

I came across the following code in ipython:

oname = args and args or '_'

What is the point of that? Why not use just args or '_'?

like image 540
elyashiv Avatar asked Nov 08 '18 14:11

elyashiv


Video Answer


1 Answers

I'm guessing this is a hold-over from ancient (2.4 or earlier) variants of Python, where the ternary operator was not yet available to the language. According to the Python Programming FAQ:

Is there an equivalent of C’s ”?:” ternary operator?

Yes, there is. The syntax is as follows:

[on_true] if [expression] else [on_false]

x, y = 50, 25
small = x if x < y else y

Before this syntax was introduced in Python 2.5, a common idiom was to use logical operators:

[expression] and [on_true] or [on_false]

However, this idiom is unsafe, as it can give wrong results when on_true has a false boolean value. Therefore, it is always better to use the ... if ... else ... form.

The line in question could now be written as either:

# Option 1
oname = args if args else '_'

# Option 2
oname = args or '_'

Both yield the same result, since in this case the [expression] portion of option 1 is identical to the [on_true] portion. As I see it, option 2 can be considered a shortened form of option 1 for cases where [expression] and [on_true] are identical. Which one you choose to use is a personal preference.

This may give us a clue as to how long it has been since the code in question has been touched!

like image 92
Jonah Bishop Avatar answered Nov 03 '22 01:11

Jonah Bishop