Python 中的非常长的 If 语句

在 Python 中有一个非常长的 if 语句。把它分成几行的最好方法是什么?我说的最好是指最可读[最普通]。

176189 次浏览

根据 PEP8,长线应该放在括号内。当使用括号时,行可以不使用反斜杠而被拆分。您还应该尝试将换行符 之后布尔运算符。

此外,如果使用代码样式检查(如 皮克斯特风格) ,则下一个逻辑行需要对代码块进行不同的缩进。

例如:

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

下面是直接来自 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)