Two blank lines are expected between functions and classes.
Anti-pattern
def func1():
pass
def func2():
pass
Best practice
def func1():
pass
def func2():
pass
Additional links
- https://www.python.org/dev/peps/pep-0008/#blank-lines
I’m using vim editor as python IDE. Below is a simple python program to calculate square root of a number:
import cmath
def sqrt():
try:
num = int(input("Enter the number : "))
if num >= 0:
main(num)
else:
complex(num)
except:
print("OOPS..!!Something went wrong, try again")
sqrt()
return
def main(num):
squareRoot = num**(1/2)
print("The square Root of ", num, " is ", squareRoot)
return
def complex(num):
ans = cmath.sqrt(num)
print("The Square root if ", num, " is ", ans)
return
sqrt()
And the warnings are :
1-square-root.py|2 col 1 C| E302 expected 2 blank lines, found 0 [pep8]
1-square-root.py|15 col 1 C| E302 expected 2 blank lines, found 1 [pep8]
1-square-root.py|21 col 1 C| E302 expected 2 blank lines, found 0 [pep8]
Can you please tell why these warnings are coming?
renatodamas
15.9k7 gold badges30 silver badges51 bronze badges
asked Nov 1, 2015 at 20:30
Amit UpadhyayAmit Upadhyay
7,1214 gold badges43 silver badges56 bronze badges
2
import cmath
def sqrt():
try:
num = int(input("Enter the number : "))
if num >= 0:
main(num)
else:
complex_num(num)
except:
print("OOPS..!!Something went wrong, try again")
sqrt()
return
def main(num):
square_root = num**(1/2)
print("The square Root of ", num, " is ", square_root)
return
def complex_num(num):
ans = cmath.sqrt(num)
print("The Square root if ", num, " is ", ans)
return
sqrt()
The previous will fix your PEP8 problems. After your import you need to have 2 new lines before starting your code. Also, between each def foo()
you need to have 2 as well.
In your case you had 0 after import, and you had 1 newline between each function. Part of PEP8 you need to have a newline after the end of your code. Unfortunately I don’t know how to show it when I paste your code in here.
Pay attention to the naming, it’s part of PEP8 as well. I changed complex
to complex_num
to prevent confusion with builtin complex
.
In the end, they’re only warning, they can be ignored if needed.
answered Nov 1, 2015 at 21:06
You need to give two blank lines between meaningful code blocks.
These include (for example):
- The import block
- Each function
8bitjunkie
12.7k9 gold badges56 silver badges70 bronze badges
answered Aug 9, 2017 at 9:59
1
Here is the link to the documentation:
PEP8 Style Guide for Python
You should add two spaces between the functions, as shown below:
import cmath
def sqrt():
try:
num = int(input("Enter the number : "))
if num >= 0:
main(num)
else:
complex_num(num)
except:
print("OOPS..!!Something went wrong, try again")
sqrt()
return
def main(num):
square_root = num ** (1 / 2)
print("The square Root of ", num, " is ", square_root)
return
def complex_num(num):
ans = cmath.sqrt(num)
print("The Square root if ", num, " is ", ans)
return
sqrt()
answered Aug 9, 2017 at 10:06
1
with warnings:-
import math
def my():
print("hello world")
my()
Without warnings:-
import math
def my():
print("hello world")
my()
Here if you see the two lines space after import statement for second code snippet which will not give any warnings.
Again if you are writing two methods definition you have two give two lines as space between your code block.
answered Aug 9, 2017 at 11:24
All answers seem to be correct. To avoid doing this by hand, you can also use the autopep8
package (pip install autopep8). The result of calling autopep8 filename.py
is the same:
import cmath
def sqrt():
try:
num = int(input("Enter the number : "))
if num >= 0:
main(num)
else:
complex(num)
except:
print("OOPS..!!Something went wrong, try again")
sqrt()
return
def main(num):
squareRoot = num**(1/2)
print("The square Root of ", num, " is ", squareRoot)
return
def complex(num):
ans = cmath.sqrt(num)
print("The Square root if ", num, " is ", ans)
return
sqrt()
PS: have a look at if __name__ == "__main__":
answered Mar 8, 2018 at 9:48
serv-incserv-inc
35.3k9 gold badges163 silver badges183 bronze badges
When to Use Two Blank Lines? PEP 8 Style Guide
The following two rules will provide you a sufficient heuristic on when to use two blank lines:
- Surround top-level function and class definitions with two blank lines.
- Insert two blank lines after the import statements if the code that follows starts with a top-level function or class definition.
The second rule is a consequence of the first rule so it could be technically ommitted.
When to Use Single Blank Lines? PEP 8 Style Guide
The following four rules will provide you a sufficient heuristic on when to use a single blank line:
- Use one or more extra single blank lines to separate groups of related functions.
- Use a single blank line in functions to separate logical sections.
- Use a single blank line to surround method definitions inside a class.
- Do not use a single blank line between related Python one-liners.
Let’s have a look at some examples in code next!
Two Blank Lines Top Level Functions
#1.1 – Surround top-level function with two blank lines.
WRONG:
import x def f(): pass f()
CORRECT:
import x def f(): pass f()
One Blank Line Non-Top-Level Function
#1.2 – Surround non-top-level function with single blank lines.
WRONG:
import x def f(): def g(): pass g() f()
CORRECT:
import x def f(): def g(): pass g() f()
Two Blank Lines Top-Level Class Definition
#1.3 – Surround top-level class definitions with two blank lines.
WRONG:
print('hello') class X: class Y: pass class Z: pass print('world')
CORRECT:
print('hello') class X: class Y: pass class Z: pass print('world')
Note that the non-top-level class definitions Y
and Z
are not surrounded with two blank lines which is correct and in accordance with the rule.
Two Blank Lines Import Statements
While many online sources state that there should be two blank lines after the import
statements before the code starts, this is not generally correct. PEP 8 only states that top-level function or class definitions should be surrounded by two blank lines!
PEP 8 doesn’t talk about import
statements specifically in regards of insertion of two blank lines!
- If the
import
block is followed by a function or class definition, you should insert two blank lines in accordance to this rule. - If the
import
block is followed by, say, a global variable definition, you shouldn’t insert two blank lines—one is enough!
Import Statements Followed by Two Blank Lines:
The following code snippet exemplifies the correct insertion of two blank lines after the import
statement. But the blank lines are not there because of the import statement. They are there because of the top-level function definition of f
.
# Correct import x import y import z def f(): pass f()
Import Statements NOT Followed by Two Blank Lines:
The following code snippet exemplifies the correct insertion of only one empty line after the import
statement because we define a global variable MY_VAR
that is neither a class nor a function definition and, thereby, shouldn’t be surrounded by two blank lines!
# Correct import x import y import z MY_VAR = 42
The logical implication is that the rule import
statements should be followed by two blank lines is incorrect!
Next, we’ll explore some examples where only one single blank line can or should be inserted.
Single Blank Lines
#3 – Use one or more extra single blank lines to separate groups of related functions.
def f1(): pass def f2(): pass def f3(): pass def g1(): pass def g2(): pass def g3(): pass
#4 – Use a single blank line in functions to separate logical sections.
def f1(): print('first') print('logical') print('section') print('second') print('logical') print('section') f1()
#5 – Use a single blank line to surround method definitions inside a class.
class X: def __init__(self): pass def x1(): pass def x2(): pass def x3(): pass x = X() x.x1() x.x2() x.x3()
A common style error is to surround method definitions by two lines instead of one because people wrongly remember rule #1.
Here’s such a wrong example:
# WRONG class X: def __init__(self): pass def x1(): pass def x2(): pass def x3(): pass x = X() x.x1() x.x2() x.x3()
Too much whitespace!
Do not surround method definitions with two blank lines!
Blank Lines Around One-Liners
#6 – Do not use a single blank line between related Python one-liners.
For example, if you write the specification of three functions for later implementation, you can simply omit the blank lines around one-liner function definitions to avoid too much whitespace in the code.
Like so:
def f1(): pass def f2(): pass def f3(): pass
Expected 2 blank lines, found 0 (E302)
Python may raise an error or informational message:
expected 2 blank lines, found 0 (E302)
expected 2 blank lines, found 1 (E302)
To fix this error, surround the top-level function or class definitions with two blank lines instead of zero or one to adhere to the PEP 8 style guide.
No! Do NOT Do This:
def f1(): pass def f2(): pass
Yes! Do This Instead:
def f1(): pass def f2(): pass
Here are some quick references for further reading.
References:
- https://stackoverflow.com/questions/2953250/python-pep8-blank-lines-convention
- https://peps.python.org/pep-0008/#blank-lines
- https://www.reddit.com/r/learnprogramming/comments/tnmhwe/when_to_use_blank_lines_in_python_in_order_to/
- https://www.flake8rules.com/rules/E302.html
Programmer Humor
While working as a researcher in distributed systems, Dr. Christian Mayer found his love for teaching computer science students.
To help students reach higher levels of Python success, he founded the programming education website Finxter.com that has taught exponential skills to millions of coders worldwide. He’s the author of the best-selling programming books Python One-Liners (NoStarch 2020), The Art of Clean Code (NoStarch 2022), and The Book of Dash (NoStarch 2022). Chris also coauthored the Coffee Break Python series of self-published books. He’s a computer science enthusiast, freelancer, and owner of one of the top 10 largest Python blogs worldwide.
His passions are writing, reading, and coding. But his greatest passion is to serve aspiring coders through Finxter and help them to boost their skills. You can join his free email academy here.