Python PEP: blank line after function definition?
我找不到任何关于这个细节的政治公众人物参考。函数定义后必须有空行?
我应该这样做吗:
1 2 | def hello_function(): return 'hello' |
或者我应该这样做:
1 2 3 | def hello_function(): return 'hello' |
当使用docstrings时,同样的问题也适用:
这是:
1 2 3 4 5 | def hello_function(): """ Important function """ return 'hello' |
或者这个
1 2 3 4 5 6 | def hello_function(): """ Important function """ return 'hello' |
编辑
这是PEP在空白行上所说的,正如FoxMaSk所评论的,但是它并没有在这个细节上说什么。
Blank Lines
Separate top-level function and class definitions with two blank
lines.Method definitions inside a class are separated by a single blank
line.Extra blank lines may be used (sparingly) to separate groups of
related functions. Blank lines may be omitted between a bunch of
related one-liners (e.g. a set of dummy implementations).Use blank lines in functions, sparingly, to indicate logical sections.
Python accepts the control-L (i.e. ^L) form feed character as
whitespace; Many tools treat these characters as page separators, so
you may use them to separate pages of related sections of your file.
Note, some editors and web-based code viewers may not recognize
control-L as a form feed and will show another glyph in its place.
阅读docstring惯例。
它说,即使函数非常明显,也必须编写一行docstring。它说:
There's no blank line either before or after the docstring.
所以我想写一些类似的代码
1 2 3 | def hello_function(): """Return 'hello' string.""" return 'hello' |
正如@moliware所指出的,docstring约定在一行docstrings下声明:
There's no blank line either before or after the docstring.
但是,它还说(在多行文档字符串下):
Insert a blank line after all docstrings (one-line or multi-line) that document a class -- generally speaking, the class's methods are separated from each other by a single blank line, and the docstring needs to be offset from the first method by a blank line.
我对这一切的解释是:空行不应该出现在任何docstring之前,并且只应该出现在某个类的docstring之后。