Code of the Day
IntermediateIdioms & structure

Type hints

Optional annotations that document intent and catch bugs before you run.

PythonIntermediate8 min read
Recommended first
By the end of this lesson you will be able to:
  • Annotate parameters and return values with types
  • Read common type hints, including containers and Optional
  • Explain that hints are checked by tools, not at runtime

Python is , but you can annotate the types you expect. don't change how the program runs — they document intent and let tools catch mismatches before you ever execute the code. They bring some of the static-typing safety from the data-and-types lesson to Python, opt-in.

Annotating functions

Add : type to parameters and -> type for the return:

def greet(name: str, times: int = 1) -> str:
    return (f"Hello, {name}! " * times).strip()

This reads as a contract at a glance: takes a string and an int, returns a string — exactly the signature-reading skill, now expressed in the code itself.

Container and optional types

Annotate what's inside collections, and mark values that might be missing:

def total(prices: list[float]) -> float:
    return sum(prices)

def find_user(id: int) -> str | None:   # returns a str, or None if not found
    ...

list[float] says "a list of floats"; str | None says "a string or None" — the modern way to express an optional value.

Hints are checked by tools, not at runtime

This surprises people: Python ignores the hints when running. Passing the wrong type doesn't raise because of the annotation — a separate type checker (like mypy or pyright, often built into your editor) reads the hints and flags mismatches before you run.

Python — editable, runs in your browser

Treat type hints as living documentation that a tool verifies for free. On larger codebases they catch a whole class of bugs early and make refactoring far safer — the same payoff TypeScript brings to JavaScript.

Where to go next

That completes Python Idioms & structure. Head over to the JavaScript / TS track to see how these same ideas — functions, objects, types, async — look in the language of the web.

Finished reading? Mark it complete to track your progress.

On this page