关于 Python 续行(Line continuation)的缩进/对齐问题

翻了一下风格指南,对于续行(Line continuation)的缩进/对齐,似乎并没有很明确的说明,只是简单提到 with 语句:

with open(path1) as file1, \
     open(path2) as file2:
    do_something()

以上代码的第二个 open 不受 4 空格缩进约束,而是跟上一个 open 对齐。

python-mode 启用了这条规则(Atom / Sublime Text / VScode 都没有,当然这些编辑器我没怎么配置,Emacs 也是加了 -Q 启动)。

同样遵循这条规则的语句还有 if:

if cond1 and \
   cond2 and \
   cond3:
    do_something()

以及链式调用:

foobar.a() \
      .b() \
      .c()

但是赋值语句又回到了 4 空格缩进:

total = 1 + \
    2 + \
    3

还有 return 语句:

def sum(a, b, c):
    return a + \
        b + \
        c

大家怎么处理?

1 个赞

平时自个续行用的比较少,倒是没咋关注过这个问题。学习了。