【发布时间】:2011-07-12 07:41:23
【问题描述】:
我在 Python 中有一个很长的 if 语句。将它分成几行的最佳方法是什么?最好的意思是最易读/最常见的。
【问题讨论】:
-
请出示代码!
标签: python
我在 Python 中有一个很长的 if 语句。将它分成几行的最佳方法是什么?最好的意思是最易读/最常见的。
【问题讨论】:
标签: python
根据PEP8,长行应放在括号中。使用括号时,可以在不使用反斜杠的情况下拆分行。您还应该尝试将换行符放在 布尔运算符之后。
此外,如果您正在使用代码样式检查,例如pycodestyle,则下一个逻辑行需要与您的代码块有不同的缩进。
例如:
if (abcdefghijklmnopqrstuvwxyz > some_other_long_identifier and
here_is_another_long_identifier != and_finally_another_long_name):
# ... your code here ...
pass
【讨论】:
E129 或使用 Andrew Clark 的解决方案 (stackoverflow.com/a/5253419/981933) 否则 PEP8 将向您抛出错误。请参阅:github.com/PyCQA/pep8/issues/126 和 github.com/PyCQA/pep8/issues/386
E129,遵守就行。没有它就很难阅读。
E129。我对任何尝试都不满意。
这是直接来自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)
【讨论】:
height有什么特别之处,后面还要休息一下?” “为什么不在width 或color 之后中断呢?”这类问题只在break时出现,不遵循严格的规则。