非常长的Python语句

rec*_*gle 89 python

我在Python中有一个很长的if语句.什么是将其分成几行的最佳方法?我认为最具可读性/普通性.

dap*_*wit 162

根据PEP8,长线应放在括号中.使用括号时,可以在不使用反斜杠的情况下拆分行.您还应该尝试布尔运算符之后放置换行符.

除此之外,如果您使用的是代码样式检查(如pycodestyle),则下一个逻辑行需要对代码块进行不同的缩进.

例如:

if (abcdefghijklmnopqrstuvwxyz > some_other_long_identifier and
        here_is_another_long_identifier != and_finally_another_long_name):
    # ... your code here ...
    pass
Run Code Online (Sandbox Code Playgroud)

  • 为了符合E129,在here_is_another_long_identifier之前再增加4个空格[..]以下安德鲁·克拉克的例子解释得最好,应该是真正的答案. (4认同)
  • 只是对您的解决方案进行评论,中断应该在“and”运算符之前。pep8的新规则。 (2认同)

And*_*ark 36

以下是PEP 8关于限制线长度的示例:

class Rectangle(Blob):

    def __init__(self, width, height,
                 color='black', emphasis=None, highlight=0):
        if (width == 0 and height == 0 and
                color == 'red' and emphasis == 'strong' or
                highlight > 100):
            raise ValueError("sorry, you lose")
        if width == 0 and height == 0 and (color == 'red' or
                                           emphasis is None):
            raise ValueError("I don't think so -- values are %s, %s" %
                             (width, height))
        Blob.__init__(self, width, height,
                      color, emphasis, highlight)
Run Code Online (Sandbox Code Playgroud)

  • 但这会导致E129,使用pep8 lint检查器在视觉上缩进行,并使用与下一个逻辑行相同的缩进. (4认同)
  • 如果将多个参数放在一行上,但随后仍然会破坏并将其余参数放在第二行上,则会损害可读性。如果不是太长,可以在每行之后打断,也可以将它们全部排成一行。“‘高度’有什么特别之处,以至于后面有一个中断?” “为什么不在‘宽度’或‘颜色’之后中断?” 这类问题只有在破解时才会出现,这并不遵循严格的规则。 (2认同)