Python 函数中 return 语句前的空行

Blank line before the return statement in a Python function

我找不到任何关于在 return 之前使用空行的 PEP 参考,所以想知道常见的做法是什么。

示例 A1:

def add(a,b):
    """ docstrings"""
    a = a + 2
    b = b + 2
    c = a +b
    return c

示例 A2:

def add(a,b):
    """ docstrings"""
    a = a + 2
    b = b + 2
    c = a +b

    return c

示例 B1:

def add(a,b):
    """ docstrings"""
    if a > b:
       c = a + b
    else:
       c = a -b
    return c

示例 B2:

def add(a,b):
    """ docstrings"""
    if a > b:
       c = a + b
    else:
       c = a -b

    return c

示例 C1:

def add(a):
    """ docstrings"""
    for i in range(3):
       a = a + i
    return a

示例 C2:

def add(a):
    """ docstrings"""
    for i in range(3):
       a = a + i

    return a

在这些用例(A、B、C)中,哪些是常见的做法?当在 return 语句之前涉及 if-else 块或循环时,有什么变化吗?

return 和空白行没有常见的做法(至少我在样式 PEP 中见过 None)。

但是有一个是关于空行和文档字符串的(见PEP 257):

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.

(强调我的)

我经常在循环后看到空行,有时在 return 之前也看到空行,但这取决于 function/loop 的长度。通常更重要的是决定一种风格(如果没有现成的惯例)并坚持下去。

正如PEP8所说:

A style guide is about consistency. Consistency with this style guide is important. Consistency within a project is more important. Consistency within one module or function is the most important.

然而,重要的是 PEP8 建议谨慎使用空行并分隔逻辑部分(我不认为它是 "return" 的逻辑部分,但 YMMV):

Use blank lines in functions, sparingly, to indicate logical sections.

(强调我的)