The PEP8 Python style guide

By

A guide to the PEP8 Python style guide: indent with 4 spaces, name variables with snake_case and classes with CamelCase, and write cleaner, pythonic code.

~~~

When you write code, you should adhere to the conventions of the programming language you use.

If you learn the right naming and formatting conventions right from the start, it will be easier to read code written by other people, and people will find your code easier to read. Shared rules also keep code reviews about the change, not about spacing.

Python defines its conventions in the PEP 8 style guide. PEP stands for Python Enhancement Proposals and it’s the place where all Python language enhancements and discussions happen. There are a lot of PEP proposals, all available at https://peps.python.org/.

PEP 8 is one of the first ones, and one of the most important, too. It defines the formatting and also some rules on how to write Python in a “pythonic” way.

You can read its full content here: https://peps.python.org/pep-0008/ but here’s a quick summary of the important points you can start with:

Before and after

Here is the same tiny function, messy first, then closer to PEP 8:

def GetTotal(Items,TaxRate):
  total=0
  for i in Items:
    total=total+i
  return total*(1+TaxRate)
def get_total(items, tax_rate):
    total = 0
    for price in items:
        total = total + price
    return total * (1 + tax_rate)

The names are in snake_case, the indent is 4 spaces and there are spaces around the operators and after the commas. The logic is the same, but the second version is much easier to scan.

Tools that check PEP 8 for you

You don’t have to remember all of this by hand. pycodestyle checks a file against PEP 8 and prints every violation with its rule number. Run it on the first version above and it reports six problems: indentation that is not a multiple of 4 (E111), missing whitespace around operators (E225) and after a comma (E231). The second version passes with no output.

Flake8 bundles pycodestyle with a few other checks. Black goes one step further and rewrites the file for you, with almost no options on purpose. Ruff is a newer linter and formatter written in Rust, much faster, and it covers the same ground. Most projects run one of these in the editor or in CI, so you rarely fix spacing by hand anymore.

Keep in mind that Black and Ruff format to 88 characters per line, not 79. Formatters also don’t rename anything, so GetTotal and Items stay wrong until you fix them yourself (Ruff flags them if you enable its N naming rules).

Tagged: Python · All topics

Want me to talk about your product? You can sponsor this site.

~~~

Related posts about python: