Python中的超长if语句

165 投票
2 回答
203589 浏览
提问于 2025-04-16 13:23

我在Python里有一个非常长的if语句。有什么好的方法可以把它分成几行呢?我说的“好”是指最容易读懂和最常见的写法。

2 个回答

54

这里有一个直接来自 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)
259

根据 PEP8 的规定,长行代码应该用括号括起来。这样一来,当你需要换行时,就可以不使用反斜杠了。你还应该尽量在布尔运算符后面换行。

另外,如果你在使用像 pycodestyle 这样的代码风格检查工具,下一行的缩进需要和你当前代码块的缩进不同。

举个例子:

if (abcdefghijklmnopqrstuvwxyz > some_other_long_identifier and
        here_is_another_long_identifier != and_finally_another_long_name):
    # ... your code here ...
    pass

撰写回答