What’s PEP 8?

It contains some conventions in coding with Python. They make the codes clearer and more beautiful. Read the full doc here. Below are just some of them in my choice.

Naming styles

  • Package & module names & function & variable: all_lower_case or short with underscore.
  • Class names: use CapWords.
  • Constant: ALL_CAPITAL_LETTERS.
  • Avoid these:

    l = 1 # lowercase letter el
    O = 1 # uppercase letter oh
    I = 1 # uppercase letter eye
      
    Capitalized_Words_With_Underscores = 1 # ugly
    

Code lay-out

Indentation

Use 4 spaces per indentation level. Note that, in this site, for a better view, I use 2 spaces for the code highlight.

# Yes
def func(...):
    commands # 4 spaces
# No
def func(...):
  commands # 2 spaces

Vertical align when break a continuous line:

# Yes
foo = long_function_name(var_one, var_two,
                         var_three, var_four)
# No
foo = long_function_name(var_one, var_two,
    var_three, var_four)

Distinguish arguments from the rest:

# Yes
def long_function_name(
        var_one, var_two, var_three,
        var_four):
    print(var_one)
# No
def long_function_name(
    var_one, var_two, var_three,
    var_four):
    print(var_one)

Tabs or spaces?

Spaces are preferred. Don’t mix tabs and spaces (not allowed in Python 3).

Max line lenght

Max of 79 characters.

Line break with operator

Operators should go with operands

# Yes
income = (salary
          + sale)
# No
income = (salary +
          sale)

Import

Imports should usually be on separate lines:

# Yes
import os
import sys
# No
import os, sys
# But yes
from subprocess import Popen, PIPE

Whitespace

Avoid extraneous whitespace:

# Yes
spam(ham[1], {eggs: 2})
foo = (0,)
if x == 4: print x, y; x, y = y, x
# No
spam( ham[ 1 ], { eggs: 2 } )
bar = (0, )
if x == 4 : print x , y ; x , y = y , x

For slices

# Yes
ham[1:9], ham[1:9:3], ham[:9:3], ham[1::3], ham[1:9:]
ham[lower:upper], ham[lower:upper:], ham[lower::step]
ham[lower+offset : upper+offset]
ham[: upper_fn(x) : step_fn(x)], ham[:: step_fn(x)]
ham[lower + offset : upper + offset]
# No
ham[lower + offset:upper + offset]
ham[1: 9], ham[1 :9], ham[1:9 :3]
ham[lower : : upper]
ham[ : upper]

Add open parenthesis/bracket right after:

# Yes
spam(1)
dct['key'] = lst[index]
# No
spam (1)
dct ['key'] = lst [index]

No need to have verticle alignment:

# Yes
x = 1
y = 2
long_variable = 3
# No
x             = 1
y             = 2
long_variable = 3

With operators:

# 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)

Def of a function:

# Yes
def complex(real, imag=0.0):
    return magic(r=real, i=imag)
# No
def complex(real, imag = 0.0):
    return magic(r = real, i = imag)

Programming Recommendations

Using not inside if:

# Yes
if foo is not None:
# No
if not foo is None:

Using Use .startswith() and .endswith() instead of string slicing:

# Yes
if foo.startswith('bar'):
# No
if foo[:3] == 'bar':

For sequences, (strings, lists, tuples), use the fact that empty sequences are false:

# Yes 
if not seq:
if seq:
# No
if len(seq):
if not len(seq):

Don’t compare boolean values to True or False using ==:

# Yes
if greeting:
# No
if greeting == True:
# Worse
if greeting is True:

Notice an error?

Everything on this site is published on Github. Just summit a suggested change or email me directly (don't forget to include the URL containing the bug), I will fix it.