This guy, Leon Sandøy, A.K.A. lemonsaurus, took the time to write and perform an informative song about PEP-8. Go watch! It’s both funny and informative 🙂
What is PEP 8?
PEP 8 is the official style guide for Python code. Guido van Rossum, Barry Warsaw and Alyssa Coghlan wrote it to make Python code look consistent, so it’s easier to read for everyone. Some of its best-known rules:
- Indent with four spaces, not tabs.
- Keep lines short (PEP 8 says 79 characters; many projects allow a bit more).
- Use
snake_casefor functions and variables,CapWordsfor classes, andUPPER_CASEfor constants. - Put spaces around operators and after commas, but not inside parentheses.
- Put imports at the top of the file, one module per line.
Let a tool do the work
You don’t have to memorize all of this. A formatter like Ruff fixes the layout for you. Take this messy function:
def CalculateTotal( prices,taxRate ):
Total=0
for p in prices :
Total+=p*(1+taxRate)
return TotalCode language: Python (python)
After running ruff format, the spacing is fixed:
def CalculateTotal(prices, taxRate):
Total = 0
for p in prices:
Total += p * (1 + taxRate)
return TotalCode language: Python (python)
A formatter won’t rename things for you, though. For that, Ruff’s linter can check the PEP 8 naming rules:
$ ruff check --select N --output-format concise messy.py
messy.py:1:5: N802 Function name `CalculateTotal` should be lowercase
messy.py:1:28: N803 Argument name `taxRate` should be lowercase
messy.py:2:5: N806 Variable `Total` in function should be lowercase
messy.py:4:9: N806 Variable `Total` in function should be lowercase
Found 4 errors.Code language: Python (python)
Rename them to calculate_total, tax_rate and total, and your code follows PEP 8. Style is only part of writing good code, though. For more, read my readable code tricks and the 12 habits of highly effective Python developers.