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

70

有时候在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中没有找到相关内容。


1
Put it in parentheses. - Peter Wood
4个回答

92

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

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风格(称为悬挂缩进)。您也可以将额外的行缩进以匹配开括号:

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部分的位置取决于你自己;我以上使用了个人偏好,但是还没有任何人对该操作符有特定的风格达成共识。


54

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.")

谢谢你的回答!我发现这两个答案是等价的,所以我接受了较早的那个。 - nedim
为 Monty Python 的参考点赞 - Mark
2
@Mark Python的引用是在原始问题中提到的。 - Peter Wood

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是倒置的逻辑。如果您能重写函数,那么这将更易读:

BONUS: 以上代码的重构揭示了另一个可读性问题: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!'

1
当一个人习惯于在一个地方声明变量后,这段代码就不再易读:您没有显示answer声明 - 这需要另一行。这是膨胀。 - WestCoastProjects
2
@javadba 不需要其他 answer 的声明。两个分支都包括了声明。 - Peter Wood
1
@PeterWood 这是真的。所以只有我评论的一半适用。 - WestCoastProjects
可变性,可变性,一切皆为可变性。 - juanchito
我也发现,当涉及到声明变量时,将其放在一个地方而不是分支中更清晰。 - antont

-1

就像这样:

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接