Thi's avatar
HomeAboutNotesBlogTopicsToolsReading
About|My sketches |Cooking |Cafe icon Support Thi
πŸ’Œ [email protected]

Python PEP 8: Style guide / Best Practices

Anh-Thi Dinh
PythonBest Practices
Left aside

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:

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.
Vertical align when break a continuous line:
Distinguish arguments from the rest:

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

Import

Imports should usually be on separate lines:

Whitespace

Avoid extraneous whitespace:
For slices
Add open parenthesis/bracket right after:
No need to have verticle alignment:
With operators:
Def of a function:

Programming Recommendations

Using not inside if:
Using Use .startswith() and .endswith() instead of string slicing:
For sequences, (strings, lists, tuples), use the fact that empty sequences are false:
Don't compare boolean values to True or False using ==:
β—†What's PEP 8?β—†Naming stylesβ—†Code layoutβ—‹Indentationβ—‹Tabs or spaces?β—‹Max line lenghtβ—‹Line break with operatorβ—‹Importβ—†Whitespaceβ—†Programming Recommendations
About|My sketches |Cooking |Cafe icon Support Thi
πŸ’Œ [email protected]
1l = 1 # lowercase letter el
2O = 1 # uppercase letter oh
3I = 1 # uppercase letter eye
4
5Capitalized_Words_With_Underscores = 1 # ugly
1# Do
2def func(...):
3    commands # 4 spaces
1# Don't
2def func(...):
3  commands # 2 spaces
1# Do
2foo = long_function_name(var_one, var_two,
3                         var_three, var_four)
1# Don't
2foo = long_function_name(var_one, var_two,
3    var_three, var_four)
1# Do
2def long_function_name(
3        var_one, var_two, var_three,
4        var_four):
5    print(var_one)
1# Don't
2def long_function_name(
3    var_one, var_two, var_three,
4    var_four):
5    print(var_one)
1# Do
2income = (salary
3          + sale)
1# Don't
2income = (salary +
3          sale)
1# Do
2import os
3import sys
1# Don't
2import os, sys
1# But yes
2from subprocess import Popen, PIPE
1# Do
2spam(ham[1], {eggs: 2})
3foo = (0,)
4if x == 4: print x, y; x, y = y, x
1# Don't
2spam( ham[ 1 ], { eggs: 2 } )
3bar = (0, )
4if x == 4 : print x , y ; x , y = y , x
1# Do
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# Don't
2ham[lower + offset:upper + offset]
3ham[1: 9], ham[1 :9], ham[1:9 :3]
4ham[lower : : upper]
5ham[ : upper]
1# Do
2spam(1)
3dct['key'] = lst[index]
1# Don't
2spam (1)
3dct ['key'] = lst [index]
1# Do
2x = 1
3y = 2
4long_variable = 3
1# Don't
2x             = 1
3y             = 2
4long_variable = 3
1# Do
2i = i + 1
3submitted += 1
4x = x*2 - 1
5hypot2 = x*x + y*y
6c = (a+b) * (a-b)
1# Don't
2i=i+1
3submitted +=1
4x = x * 2 - 1
5hypot2 = x * x + y * y
6c = (a + b) * (a - b)
1# Do
2def complex(real, imag=0.0):
3    return magic(r=real, i=imag)
1# Don't
2def complex(real, imag = 0.0):
3    return magic(r = real, i = imag)
1# Do
2if foo is not None:
1# Don't
2if not foo is None:
1# Do
2if foo.startswith('bar'):
1# Don't
2if foo[:3] == 'bar':
1# Do
2if not seq:
3if seq:
1# Don't
2if len(seq):
3if not len(seq):
1# Do
2if greeting:
1# Don't
2if greeting == True:
1# Worse
2if greeting is True: