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?
The new line character in Python is \n .
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.
Blank lines improve readability by setting off sections of code that are logically related. Two blank lines should always be used in the following circumstances: Between sections of a source file. Between class and interface definitions.
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.
There's no common practice (at least I've seen None in the style PEPs) for return
s 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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With