Python PEP 8: Style guide

Anh-Thi Dinh

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:
    • 1l = 1 # lowercase letter el
      2O = 1 # uppercase letter oh
      3I = 1 # uppercase letter eye
      4
      5Capitalized_Words_With_Underscores = 1 # ugly

Code layout

Indentation

Use 4 spaces per indentation level. Note that, in this site, for a better view, I use 2 spaces for the code highlight.
1# YES
2def func(...):
3    commands # 4 spaces
1# NO
2def func(...):
3  commands # 2 spaces
Vertical align when break a continuous line:
1# YES
2foo = long_function_name(var_one, var_two,
3                         var_three, var_four)
1# NO
2foo = long_function_name(var_one, var_two,
3    var_three, var_four)
Distinguish arguments from the rest:
1# YES
2def long_function_name(
3        var_one, var_two, var_three,
4        var_four):
5    print(var_one)
1# NO
2def long_function_name(
3    var_one, var_two, var_three,
4    var_four):
5    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
1# YES
2income = (salary
3          + sale)
1# NO
2income = (salary +
3          sale)

Import

Imports should usually be on separate lines:
1# YES
2import os
3import sys
1# NO
2import os, sys
1# But yes
2from subprocess import Popen, PIPE

Whitespace

Avoid extraneous whitespace:
1# YES
2spam(ham[1], {eggs: 2})
3foo = (0,)
4if x == 4: print x, y; x, y = y, x
1# NO
2spam( ham[ 1 ], { eggs: 2 } )
3bar = (0, )
4if x == 4 : print x , y ; x , y = y , x
For slices
1# YES
2ham[1:9], ham[1:9:3], ham[:9:3], ham[1::3], ham[1:9:]
3ham[lower:upper], ham[lower:upper:], ham[lower::step]
4ham[lower+offset : upper+offset]
5ham[: upper_fn(x) : step_fn(x)], ham[:: step_fn(x)]
6ham[lower + offset : upper + offset]
1# NO
2ham[lower + offset:upper + offset]
3ham[1: 9], ham[1 :9], ham[1:9 :3]
4ham[lower : : upper]
5ham[ : upper]
Add open parenthesis/bracket right after:
1# YES
2spam(1)
3dct['key'] = lst[index]
1# NO
2spam (1)
3dct ['key'] = lst [index]
No need to have verticle alignment:
1# YES
2x = 1
3y = 2
4long_variable = 3
1# NO
2x             = 1
3y             = 2
4long_variable = 3
With operators:
1# YES
2i = i + 1
3submitted += 1
4x = x*2 - 1
5hypot2 = x*x + y*y
6c = (a+b) * (a-b)
1# NO
2i=i+1
3submitted +=1
4x = x * 2 - 1
5hypot2 = x * x + y * y
6c = (a + b) * (a - b)
Def of a function:
1# YES
2def complex(real, imag=0.0):
3    return magic(r=real, i=imag)
1# NO
2def complex(real, imag = 0.0):
3    return magic(r = real, i = imag)

Programming Recommendations

Using not inside if:
1# YES
2if foo is not None:
1# NO
2if not foo is None:
Using Use .startswith() and .endswith() instead of string slicing:
1# YES
2if foo.startswith('bar'):
1# NO
2if foo[:3] == 'bar':
For sequences, (strings, lists, tuples), use the fact that empty sequences are false:
1# YES
2if not seq:
3if seq:
1# NO
2if len(seq):
3if not len(seq):
Don't compare boolean values to True or False using ==:
1# YES
2if greeting:
1# NO
2if greeting == True:
1# Worse
2if greeting is True: