【问题标题】:How to make a line break on the Python ternary operator?如何在 Python 三元运算符上换行?
【发布时间】:2015-05-07 22:52:39
【问题描述】:

有时在 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 中没有找到它。

【问题讨论】:

  • 把它放在括号里。

标签: python line-breaks


【解决方案1】:

请记住 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!'

【讨论】:

  • 这在人们有点习惯于在一个地方看到一个声明的变量之后就不那么可读了:你没有显示answer声明 - 这还需要另一行。这是膨胀。
  • @javadba 不需要answer 的其他声明。两个分支都包含一个声明。
  • @PeterWood 这是真的。所以我的评论只有一半适用。
  • 可变性,可变性,一切都是可变性
【解决方案2】:

PEP8 说preferred way of breaking long lines is using parentheses

包装长行的首选方法是使用 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.")

【讨论】:

  • 感谢您的回答!我发现这两个答案相同,所以我接受了较旧的答案。
  • 支持 monty python 参考
  • @Mark Python 引用在原始问题中。
【解决方案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 一切缩进一步多的样式(称为hanging 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 部分的确切位置取决于您;我在上面使用了我的个人偏好,但目前还没有任何人都同意的运营商的特定风格。

【讨论】:

    猜你喜欢
    • 2012-08-08
    • 2020-01-30
    • 2022-01-04
    • 2021-09-18
    • 2021-02-22
    • 2011-05-05
    • 1970-01-01
    • 2018-09-18
    • 2015-02-07
    相关资源
    最近更新 更多