Stop 08 · Intermediate PythonTopics · 5/10

Type Hints

Part of the Python Roadmap

In short

Type hints describe what kinds of values your functions expect and return. Python doesn't enforce them, but your editor and tools like mypy use them to catch bugs before you even run the code.

Type hints like def add(a: int, b: int) -> int: describe the expected types of arguments and return values. Python doesn't enforce them at runtime, but editors and tools like mypy use them to catch mistakes early.

The jaadu sticks bright labels onto two identical white jars of powder on a kitchen shelf, one with a sugar cube picture and one with a salt shaker picture.

Think of it like this

Labels on kitchen jars

Sugar and salt look the same in plain jars. Labels don't stop anyone from putting salt in the sugar jar, but they make the mistake obvious. Type hints are those labels: Python still lets you put anything anywhere, but you, your teammates and your editor can see when something doesn't match.

Watch it happen

Without and with hints

def total(items, rate)

  • What is items? A list? A dict?
  • Is rate 18 or 0.18?
  • What comes back?
  • Bugs show up at runtime

def total(items: list[float], rate: float) -> float

  • Clear input types
  • Editor autocompletes correctly
  • mypy flags wrong calls
  • The signature is the documentation

Hints cost a few characters and save hours of guessing. Add them to function signatures first, where they help the most.

The big ideas

What you need to know

Basic syntax

name: str for variables and parameters, and -> int for return types. Built-in generics like list[str] and dict[str, int] work in Python 3.9+.

Unions and None

int | None means 'an int or None' (Python 3.10+). Use it for optional values.

Not enforced

Python ignores hints at runtime. Passing a str where int is hinted still runs, so use mypy or your editor to check.

Going further

TypedDict for dict shapes, Literal['UPI', 'Card'] for fixed choices, and Callable[[int], str] for functions.

See it in code

Walk through the code

python
1from typing import Literal, TypedDict2from collections.abc import Callable3 4type Rupees = float                     # Python 3.12 type alias5 6class Order(TypedDict):7    id: int8    city: str9    amount: Rupees10    method: Literal["UPI", "Card", "Cash"]11 12def find_order(orders: list[Order], order_id: int) -> Order | None:13    for order in orders:14        if order["id"] == order_id:15            return order16    return None17 18def apply_all(orders: list[Order], fn: Callable[[Rupees], Rupees]) -> list[Rupees]:19    return [fn(o["amount"]) for o in orders]20 21orders: list[Order] = [22    {"id": 1, "city": "Indore", "amount": 640.0, "method": "UPI"},23    {"id": 2, "city": "Patna", "amount": 1200.0, "method": "Card"},24]25found = find_order(orders, 2)26if found is not None:27    print(found["city"])                # Patna28print(apply_all(orders, lambda a: a * 1.18))

1/6The type statement (new in 3.12) gives a meaningful name to float.

A type alias, a TypedDict with a Literal field, an optional return and a Callable parameter. Run mypy on it to check.

Save yourself the pain

Common mistakes

Oops

Assuming def add(a: int, b: int) will reject add('2', '3').

Do this instead

It runs and returns '23'. Run mypy or use your editor's checker to catch it.

Oops

Writing def f(x: list = []) and thinking the hint makes the default safe.

Do this instead

Hints don't change behaviour. Use x: list[int] | None = None and create the list inside.

Your mission

Type your old code

~25 min

Quick check

What happens at runtime if you pass a string to def square(n: int) -> int?

Go deeper

  1. 1Add type hints to the functions in one of your earlier projects.
  2. 2Use list[str], dict[str, int] and str | None in your hints.
  3. 3Notice how VS Code's suggestions improve once hints are added.

More topics at this stop

Stuck on this topic? Ask an Insider

Get 1:1 guidance from people who've walked this exact path — on the InsideEdge app.

Download
InsideEdge