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

问题描述 投票:0回答:4

有时在 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
4个回答
83
投票

您始终可以使用括号将逻辑线扩展到多条物理线

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

这叫做隐式连接

上面使用了 PEP8 everything-indented-one-step-more 风格(称为 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 列最大值。

你把

if
else
部分放在哪里取决于你;我在上面使用了我的个人偏好,但是还没有任何人都同意的操作符的特定样式。


53
投票

PEP8 说 打断长行的首选方法是使用括号

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

11
投票

牢记Python之禅的建议: “可读性很重要。”

三元运算符在一行时最易读。

x = y if z else w

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

因此,与其尝试使用括号来换行,不如将其转换为常规的

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!'

0
投票

就这样:

if does_not_haggle(brian): answer = 'Ten for that? You must be mad!'
else: "It's worth ten if it's worth a shekel."
© www.soinside.com 2019 - 2024. All rights reserved.