PEP8:可视缩进的连续行超出了缩进范围

26

我有一行代码,超出了规定长度,在进行Pep8错误测试时会报告:行太长。因此,我尝试使用斜杠('\')来解决这个问题,但是我得到了一个“续行被过度缩进”的可视缩进错误。我该怎么做才能解决这个问题?

输入图像描述

我尝试过的方法:

if first_index < 0 or second_index > \
   self._number_of_plates - 1:
    raise ValueError

continuation line over-indented for visual indent

if first_index < 0 \ 
   or second_index > \
   self._number_of_plates - 1:
    raise ValueError

continuation line over-indented for visual indent

if first_index < 0 or \
   second_index > self._number_of_plates - 1:
    raise ValueError

continuation line over-indented for visual indent

if first_index \
   < 0 or second_index \
   > self._number_of_plates - 1:
     raise ValueError

continuation line over-indented for visual indent
4个回答

34

使用延伸行反斜杠的问题在于会产生尾随空格,这可能会破坏您的代码。这是一个流行的解决方法,符合PEP8标准:

if (first_index < 0 or
    second_index > self._number_of_plates - 1):

1
谢谢David,但是现在我用那行代码出现了“续行符与下一逻辑行没有区别”的错误。编辑:已修复! - Sc4r
5
针对未来读者 - 这意味着下一行具有相同的缩进,因此在这种情况下,上面代码中的第二行可以向右移动一个制表符。 - Dimath
在我看来,缩进第二行会严重影响可读性。我的技巧是删除括号,并用反斜杠标记行继续。唯一的问题是,在单个“with”中尝试使用多个“open()”上下文管理器时,它无法修复任何问题。添加括号会导致完全的语法错误,这让我有点好奇它如何与标准元组解析不同。 - Darren Ringer

1

连续行缩进比视觉缩进更深。

反模式 在此示例中,“World”字符串的缩进比应有的多两个空格。

print("Python", ("Hello",
                   "World"))

最佳实践。
print("Python", ("Hello",
                 "World"))

参考文献:https://www.flake8rules.com/rules/E127.html


Flake8规则中的print()示例过于简单。一个来自真实世界的具体代码示例会更加合适。 - Jari Turkia

0

对于过长的行(例如> 79个字符),您可以使用括号来分组条件:

if (first_index < 0 
        or second_index > self._number_of_plates - 1
        or condition2
        and candition3):
    raise ValueError

请注意,任何布尔条件(orand)都应该在条件之前的行首。

在您的情况下,由于 if (...) 结构有一个特殊规则:

当 if 语句的条件部分足够长以至于需要跨多行编写时,值得注意的是,一个两个字符的关键字(即 if),加上一个空格,再加上一个开括号,会为后续的多行条件自然地创建一个 4 空格缩进。这可能会产生视觉上的冲突,因为嵌套在 if 语句内部的缩进代码块也会自然地缩进到 4 个空格。本 PEP 对如何(或是否)进一步在视觉上区分这些条件行与 if 语句内部的嵌套代码块没有明确的立场。在这种情况下可接受的选项包括但不限于:

# No extra indentation.
if (this_is_one_thing and
    that_is_another_thing):
    do_something()

# Add a comment, which will provide some distinction in editors
# supporting syntax highlighting.
if (this_is_one_thing and
    that_is_another_thing):
    # Since both conditions are true, we can frobnicate.
    do_something()

# Add some extra indentation on the conditional continuation line.
if (this_is_one_thing
        and that_is_another_thing):
    do_something()

(还请参见下面关于二元运算符前后是否换行的讨论。)
来源:PEP 8风格指南

0

这就是流行的black格式化程序所做的事情:

if (
    first_index < 0
    or second_index > self._number_of_plates - 1
):
    raise ValueError

我认为这看起来很好。然而,最好重构一下代码,以免一开始就有7个缩进级别!


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