cleancode.in

Clean code in Python

PEP 8 is Python’s style guide: 4 spaces a level, lines of 79 characters at most, functions and variables in lowercase with underscores, classes in CapWords. Its rules in its own words, then one function cleaned up.

What does PEP 8 ask for?

  • One of Guido’s key insights is that code is read much more often than it is written. source

From PEP 8.

How should Python code look?

  • Four spaces a level. source
  • Lines of 79 characters at most. source

What else does it ask?

  • Consistency inside a project matters more than consistency with the guide. source
  • A comment that disagrees with the code is worse than none. source

How are names written in Python?

KindExampleRule
TypesShoppingCartClasses in CapWords. source
Functionsadd_itemFunctions in lowercase with underscores. source
Variablesitem_countVariables like functions. source
ConstantsMAX_ITEMSConstants in capitals with underscores. source

What does cleaner Python look like?

Before
def calc(l, t):
    # loop over the items
    s = 0
    for i in l:
        s = s + i["p"] * i["q"]
    return s + s * t
After
DEFAULT_TAX_RATE = 0.18


def order_total(items, tax_rate=DEFAULT_TAX_RATE):
    """Return the total of the items, tax added."""
    subtotal = sum(item["price"] * item["quantity"] for item in items)
    return subtotal * (1 + tax_rate)

What changed?

  • Names say what they hold: order_total, items, subtotal.
  • Function and variables in lowercase with underscores. source
  • The rate is a named constant in capitals, with a default. source
  • The comment that repeated the loop is gone; a docstring says what comes back. source
  • sum() replaces the loop and its running total.