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 cleaner Python look like?
def calc(l, t):
# loop over the items
s = 0
for i in l:
s = s + i["p"] * i["q"]
return s + s * tDEFAULT_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.
Other languages
More on clean code: comments, functions, naming and the checklist.