我已阅读pep8 中的空白行部分。它说我们应该用空行包围顶级函数,但它没有说明任何有关 if 语句的信息。
我对 Python 中的顶层是什么做了一些挖掘,它似乎是任何没有缩进的东西。这是否意味着 if 语句应该被空行包围?if 语句被视为函数吗?
我在堆栈溢出上找不到任何与此相关的内容。
"""
my cool and interesting program!
"""
import this_module
import that_module
import another_module
def procedure_to_do_this(*args):
if args:
print("the caller says %s!" % args[0])
elif not args:
print("the caller is too shy to say anything ;c")
else:
print("if you've reached this point, there's no turning back")
return something
procedure_to_do_this()
Run Code Online (Sandbox Code Playgroud)
这是您通常形成 if/elif/else 结构的方式,但是在大多数情况下,该结构是否符合代码的其余部分对您来说是主观的,当然,如果您觉得有太多,您可以更改它如果您想在其中一个条件子句中添加代码并且想要区分条件,则可以在一个条件结束后添加一个额外的换行符,例如:
if this:
<a lot of code>
<a lot of nice code>
<a lot of long code>
<newline>
elif that:
<a lot of other code>
Run Code Online (Sandbox Code Playgroud)
等等。
请始终记住,PEP8 是一个简单的样式指南[行],它绝不是决定代码的整体设计,因为当存在良好或特定的代码时,它本身就取决于人们认为良好的样式的外观。 。
并非所有代码在某种风格下看起来都很好,所以这就是为什么它是一个指南,而不是 Python 严格强制执行并已在解释器中实现的内容。