Search code examples
pythonpython-2.7python-3.xpep8

Blank line before the return statement in a Python function


I can't find any PEP reference to the use of a blank line before return so would like to know what is the common practice.

Example A1:

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

Example A2:

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

    return c

Example B1:

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

Example B2:

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

    return c

Example C1:

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

Example C2:

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

    return a

Which ones are the common practice in these use cases (A, B, C)? Does anything change when a block of if-else or a loop is involved before the return statement?


Solution

  • There's no common practice (at least I've seen None in the style PEPs) for returns and blank lines.

    But there is one regarding blank lines and the docstring (see PEP 257):

    There's no blank line either before or after the docstring.

    But also:

    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.

    (Emphasis mine)

    I've often seen blank lines after loops, also sometimes blank lines before return but that depends on the length of the function/loop. It's often more important to decide on one style (if there's no existing convention) and stick to it.

    As PEP8 put it:

    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.

    However it's important that PEP8 recommends to use blank lines sparingly and to separate logical sections (I don't think it's a logical section to "return" but YMMV):

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

    (Emphasis mine)