9

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 '_'?

jpp
  • 159,742
  • 34
  • 281
  • 339
elyashiv
  • 3,623
  • 2
  • 29
  • 52

1 Answers1

9

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!

Jonah Bishop
  • 12,279
  • 6
  • 49
  • 74
  • Good info, thanx! – Rocky Li Nov 08 '18 at 14:26
  • 1
    I'm not sure I agree it's a duplicate. The question isn't whether or not a ternary operator exists, but _why_ the `[value] and [value] or [alternate_value]` syntax is used in this case. – Jonah Bishop Nov 08 '18 at 14:31
  • 1
    Why not `oname = args or '_'`? – L3viathan Nov 08 '18 at 14:32
  • @tobias_k I'm referring to "should probably now be written as" – L3viathan Nov 08 '18 at 14:37
  • @L3viathan Oh, okay, yes, I agree. Although it could still be debateable whether that's good style. – tobias_k Nov 08 '18 at 14:39
  • 1
    I've updated my answer to include both possibilities, since both are valid and yield the same result. I prefer the former, since it's using the built-in ternary operator and keeps the code consistent with the idea of what was there before. – Jonah Bishop Nov 08 '18 at 14:40
  • I've added further clarification. I believe option 2 is simply a shortened form of option 1, made possible by `[expression]` being identical to `[on_true]`. In the end, which you choose likely comes down to personal preference. The end result is the same (though there could be performance differences between the two). – Jonah Bishop Nov 08 '18 at 14:49