Python · Module 13 · Lesson 31 min read

Code Style & Type Hints

PEP 8: the Python style guide

  • 4 spaces per indent level, never tabs.
  • snake_case for variables and functions, PascalCase for classes, UPPER_CASE for constants.
  • Spaces around operators: x = a + b.
  • Keep lines reasonably short (79–100 characters).
  • Imports at the top: standard library, then third-party, then your own.

Let tools do it: black or ruff format formats your code, and ruff finds problems.

Type hints

They describe what types a function expects and returns. Python doesn't enforce them at runtime, but editors and mypy use them to catch bugs before you run the code.

Modern syntax (Python 3.9+ / 3.10+)

Old (typing)Modern
List[int]list[int]
Dict[str, int]dict[str, int]
Optional[str]str | None
Union[int, float]int | float

Docstrings

A string as the first line of a function explains what it does: """Return the average, or None if the list is empty."""

▶️ Runs in the app.

Example

Python
from dataclasses import dataclass

MAX_SCORE = 100

def average(nums: list[float]) -> float | None:
    """Return the average of nums, or None if the list is empty."""
    if not nums:
        return None
    return sum(nums) / len(nums)

def grade(score: int) -> str:
    """Convert a 0–100 score into a letter grade."""
    if not 0 <= score <= MAX_SCORE:
        raise ValueError(f"score must be 0–{MAX_SCORE}")
    return "A" if score >= 90 else "B" if score >= 75 else "C"

@dataclass
class Student:
    name: str
    scores: list[int]

    def report(self) -> dict[str, float | None]:
        return {"average": average(self.scores)}

print(average([1.0, 2.0, 3.0]))           # 2.0
print(grade(88))                          # B
print(Student("Ana", [90, 80]).report())  # {'average': 85.0}