Python行中断很长“x1为y1,x2为y2,x3为y3”语句

时间:2015-07-11 00:44:01

标签: python syntax

我想打破一个长篇陈述,如:

with X1() as y1, X2() as y2, X3() as y3:  # Really long line
  # Do something

我试过了:

with (
    X1() as y1,
    X2() as y2,
    X3() as y3):
  # Do something

但这是语法错误。似乎以下工作,但我发现它相对难以阅读:

with X1(
    ) as y1, X2(
    ) as y2, X3(
    ) as y3:
  # Do something

对于如何最好地格式化这样的长with语句,有什么建议吗?感谢。

1 个答案:

答案 0 :(得分:2)

with X1() as y1, \
    X2() as y2, \
    X3() as y3:

试试吧。我认为将个别陈述保持为一行非常重要。反斜杠有助于保持明确的>隐式的Python风格。

参考此处:https://www.python.org/dev/peps/pep-0008/