如何在Python三元运算符上换行?

2024-04-16 13:05:57 发布

您现在位置:Python中文网/ 问答频道 /正文

有时Python中包含三元运算符的行太长:

answer = 'Ten for that? You must be mad!' if does_not_haggle(brian) else "It's worth ten if it's worth a shekel."

有没有推荐的方法用三元运算符在79个字符处换行?我在PEP 8里没有找到。


Tags: answeryouforifthatnot运算符be
3条回答

您始终可以用括号扩展logical line across multiple physical lines

answer = (
    'Ten for that? You must be mad!' if does_not_haggle(brian)
    else "It's worth ten if it's worth a shekel.")

这叫做implicit line joining

上面使用的是PEP8,每样东西都缩进了一步(称为ahanging indent)。您还可以缩进额外的行以匹配左括号:

answer = ('Ten for that? You must be mad!' if does_not_haggle(brian)
          else "It's worth ten if it's worth a shekel.")

但这会让你更快地达到80列的最大值。

精确地把ifelse部分放在哪里取决于您;我在上面使用了我的个人偏好,但是对于运算符没有任何人同意的特定样式。

记住这条来自《Python禅》的建议: “可读性很重要。”

当三元运算符都在一行上时,它是最可读的。

x = y if z else w

当条件或变量将行推过79个字符(参见PEP8)时,可读性开始受到影响。(可读性也是dict/list理解最好保持简短的原因。)

因此,如果您将它转换为一个常规的if块,您可能会发现它更具可读性,而不是试图使用括号打断行。

if does_not_haggle(brian):
    answer = 'Ten for that? You must be mad!'
else:
    answer = "It's worth ten if it's worth a shekel."

另外:上述重构揭示了另一个可读性问题:does_not_haggle是反向逻辑。如果您可以重写函数,这将更具可读性:

if haggles(brian):
    answer = "It's worth ten if it's worth a shekel."
else:
    answer = 'Ten for that? You must be mad!'

PEP8说preferred way of breaking long lines is using parentheses

The preferred way of wrapping long lines is by using Python's implied line continuation inside parentheses, brackets and braces. Long lines can be broken over multiple lines by wrapping expressions in parentheses. These should be used in preference to using a backslash for line continuation.

answer = ('Ten for that? You must be mad!'
          if does_not_haggle(brian)
          else "It's worth ten if it's worth a shekel.")

相关问题 更多 >