Part 11 / Topic 10 of 12
Code style and tools
PEP 8 is the official style guide for Python code. Same style everywhere = code that is easy to read, like traffic rules everyone follows.
PEP 8 essentials
| Rule | Example |
|---|---|
| 4 spaces per indent, no tabs | return total |
snake_case for functions and variables |
cart_total, discount_percent |
PascalCase for classes; exceptions end in Error |
InsufficientFundsError |
UPPER_SNAKE for constants |
GST_RATE = 0.18 |
| Lines of at most 79 (many teams use 88) characters | split long calls over lines |
| Two blank lines between top-level functions/classes | |
| Imports at the top: standard library, third-party, your own | import json / import pytest / import shop |
Spaces around = in code, none in keyword arguments |
x = 5, f(rate=0.18) |
Ruff: linter and formatter
A linter finds likely bugs and style problems (unused imports, undefined names). A formatter rewrites the layout of your code (spaces, line breaks) automatically. Ruff does both and is very fast.
python -m pip install ruff
ruff check . # lint: list problems
ruff check --fix . # fix the ones that are safe to fix
ruff format . # format every file
ruff format --check . # only report files that would change (useful in CI)
pre-commit is a tool that runs checks like Ruff automatically each time you git commit (section 11). You list the checks in a file named .pre-commit-config.yaml. Worth setting up once your project has a team.
Docstrings (Google style)
A docstring (Part 5) explains what a function does. The Google style adds sections for arguments, return value and errors:
def line_total(price: float, qty: int) -> float:
"""Return the cost of one cart line (price x quantity).
Args:
price: Price of one item in rupees. Must not be negative.
qty: How many items. Must be at least 1.
Returns:
price * qty
Raises:
ValueError: If price is negative or qty is less than 1.
"""
if price < 0 or qty < 1:
raise ValueError("bad price or quantity")
return price * qty
print(line_total(60, 5)) # 300
See shop.py for more.
Done here? The practice set for Part 11 — 7 exercises with solutions — is on the part page.