PEP 8, sometimes spelled PEP8 or PEP-8, is a document that provides guidelines and best practices on how to write Python code. It was written in 2001 by Guido van Rossum, Barry Warsaw, and Nick Coghlan. The primary focus of PEP 8 is to improve the readability and consistency of Python code.
PEP 8 specifies the following rules for the inline comments. Start comments with the # and single space. Use inline comments carefully. We should separate the inline comments on the same line as the statement they refer.
I try to adhere to the style guide for Python code (also known as PEP 8). Accordingly, the preferred way to name a class is using CamelCase: Almost without exception, class names use the CapWords convention.
PEP8 is for humans but your program will run even if you do not follow it. If you do not share your code and do not plan to do so, do whatever you want. If you plan to share some part of your code someday, then you should follow PEP8.
PEP8 says to avoid "More than one space around an assignment (or other) operator to align it with another" and "never use more than one space" around math operators, but I don't follow this.
I often add "extraneous whitespace" when neighboring lines are related or very similar, but not quite the same:
search_start = (f - f_1/3) * n/fs
search_stop = (f + f_1/3) * n/fs
b_lpf, a_lpf = filter(N, 2*pi*fc, 'low', analog=True)
b_hpf, a_hpf = filter(N, 2*pi*fc, 'high', analog=True)
p[x > 1] = np.cosh(order * np.arccosh( x[x > 1]))
p[x < -1] = (1 - 2 * (order % 2)) * np.cosh(order * np.arccosh(-x[x < -1]))
b0 = (1 + cos(w0))/2
b1 = -(1 + cos(w0))
Similarly, it's annoying that I get code style warnings for arrays of numbers formatted in the readable way that they are normally formatted by the library itself:
a = array([[-0.198, 0.248, -1.17 , -0.629, 1.378],
[-1.315, 0.947, -0.736, -1.388, 0.389],
[ 0.241, -0.98 , 0.535, 0.951, 1.143],
[-0.601, 1.286, -0.947, 0.037, -0.864],
[ 0.178, -0.289, -1.037, -1.453, -0.369]])
This produces a bunch of E201 E202 E222 violations.
PEP8 would rather have it formatted it like this, apparently, because we can't ever have extra whitespace before commas or after brackets, even if it improves readability:
a = array([[-0.198, 0.248, -1.17, -0.629, 1.378],
[-1.315, 0.947, -0.736, -1.388, 0.389],
[0.241, -0.98, 0.535, 0.951, 1.143],
[-0.601, 1.286, -0.947, 0.037, -0.864],
[0.178, -0.289, -1.037, -1.453, -0.369]])
The "79 characters per line" part is nonsense. Their very own example shows how unreadable code becomes when doing this:
class Rectangle(Blob):
def __init__(self, width, height,
color='black', emphasis=None, highlight=0):
if width == 0 and height == 0 and \
color == 'red' and emphasis == 'strong' or \
highlight > 100:
raise ValueError("sorry, you lose")
if width == 0 and height == 0 and (color == 'red' or
emphasis is None):
raise ValueError("I don't think so -- values are %s, %s" %
(width, height))
Blob.__init__(self, width, height,
color, emphasis, highlight)
It's like try-
ing to read
a news arti-
cle written
like this.
80-column terminals havn't been a serious development environment for over a decade. When I do need to edit from a crippled 80x25 environment in a pinch, editor wrapping is a minor inconvenience; I'm not going to maim my code during normal development just to avoid that.
120 column wrapping is perfectly sensible for modern development, and I have no problem with 140. This guideline is obsolete and following it results in ugly, hard-to-read code.
PEP8 says
Note that most importantly, the """ that ends a multiline docstring should be on a line by itself, and preferably preceded by a blank line, e.g.:
"""Return a foobang Optional plotz says to frobnicate the bizbaz first. """
I find this rather bizarre, since it's just "extraneous whitespace" and treats opening quotations differently from closing quotations for no obvious reason.
A rationale is given is in PEP 257:
The BDFL recommends inserting a blank line between the last paragraph in a multi-line docstring and its closing quotes, placing the closing quotes on a line by themselves. This way, Emacs' fill-paragraph command can be used on it.
Emacs, really? Everyone should do weird things to cater to the idiosyncrasies of a particular command in a particular editing tool?
I also think it's weird to put the beginning of the docstring on the same line as the quotes (not required, but recommended), while insisting that the closing quotations be on their own line. I think this is more logical, and should be used for both single line and multi-line docstrings:
def foobang(bizbaz, plotz=None):
"""
Return a foobang
Optional plotz says to frobnicate the bizbaz first.
"""
if plotz is not None:
...
Update: The bold part has been removed and now it just says to "place the closing quotes on a line by themselves", and that the "summary line may be on the same line as the opening quotes or on the next line".
I don't agree with this:
- Imports should usually be on separate lines, e.g.:
Yes: import os
import sys
No: import sys, os
I always write simple imports together. I don't see any advantage to writing them all on separate lines: all it does is add bloat to the top of each source file, and turn something concise and easy to type into something that's borderline boilerplate, eg. something that's so verbose it starts to be tempting to copy and paste from other files.
This is instantly readable and understandable:
import sys, os, time, gc, inspect, math, doctest
It's short, easy to skim, and easy to add to. I do use multiple import
statements if there are too many on one line, of course, or if I need a from
import.
I also do generally keep standard library imports separate from imports of my own modules and other libraries, which agrees with the concept of grouping PEP8 recommends.
Standards are critical and PEP 8 is a very good style guide that I insist on. The only guideline I disagree with is the spacing around mathematical operators. For example PEP8 insists on the following spacings
Without PEP8 With PEP8
----------------------------------------------------------------
y = sqrt(x**2 + y**2) y = sqrt(x ** 2 + y ** 2)
a*x**3 + b*x**2 + c*x + d a * x ** 3 + b * x ** 2 + c * x + d
10**(a*x + b) 10 ** (a * x + b)
F = V/(sqrt(g*h) + epsilon) F = V / (sqrt(g * h) + epsilon)
a*cos(nx/pi) + b*sin(nx/pi) a * cos(nx / pi) + b * sin(nx / pi)
I am trying to conform, but this is the one area where I am struggling. Do anyone else also feel that PEP8 spacing makes mathematics harder to read?
Update:
PEP8 was corrected to recommend the formatting on the left while discouraging the formatting on the right:
Yes:
i = i + 1 submitted += 1 x = x*2 - 1 hypot2 = x*x + y*y c = (a+b) * (a-b)
No:
i=i+1 submitted +=1 x = x * 2 - 1 hypot2 = x * x + y * y c = (a + b) * (a - b)
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