"a and a or b" 的目的是什么?

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

我在 ipython 中遇到了以下代码:

oname = args and args or '_'

这样做有什么意义?为什么不只使用 args or '_'

我猜这是 Python 的古老(2.4 或更早版本)变体的遗留问题,其中三元运算符还不适用于该语言。根据 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.

有问题的行现在可以写成:

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

# Option 2
oname = args or '_'

两者产生相同的结果,因为在这种情况下,选项 1 的 [expression] 部分与 [on_true] 部分相同。在我看来,对于 [expression][on_true] 相同的情况,选项 2 可以被视为选项 1 的缩写形式。您选择使用哪个是个人喜好。

这可能会给我们一些线索,让我们知道自从有问题的代码被触动以来已经有多久了!