Python, properly · Chapter 33 of 42

Type hints

By the end of this chapter you can annotate functions and data, handle None and unions the way mypy expects, write generic functions, and use mypy --strict to find bugs before the code runs. Build it in your browser: a real editor and terminal, AI that explains, and tests that tell you when it works.

  • Part: Pythonic and typed
  • 4 tasks
  • Python
  • In the all labs plan

The first 2 chapters of Python, properly are free. This one comes with the all labs plan.

Why you need this

Last night a script passed a dish's name where its price belonged, and a bill printed Naan Naan Naan instead of 120 rupees. Rafiq caught it by hand. Kunal says the codebase is now big enough that nobody can keep every function's inputs in their head: the code should say what it expects, and a tool should check it.

Python never checks types on its own. Type hints write the types down; mypy reads them and reports every place they do not fit, without running anything. Every modern Python library ships hints, editors use them for autocomplete, and Pydantic (the next chapter) turns them into runtime validation, which is how the AI frameworks read and check data.

What you build: 4 tasks

Each task has tests. You write the code in the lab's editor and press Check.

  1. Task 1

    typed_menu.py: a typed menu

    With type hints everywhere, so that mypy --strict typed_menu.py finds no errors, write:

    Dish, a TypedDict with the six keys of a dish in menu.json (id, name, category, price, spice, available), each with its type;

    load_menu(path), the list of Dish read from that JSON file;

    find_dish(menu, dish_id), the Dish with that id, or None;

    price_of(menu, dish_id), the dish's price as an int, raising KeyError when there is no such dish.

    The check runs them on the real menu (the price of chole is 150), then runs mypy on code that uses them: right uses must pass, wrong ones must be errors (using find_dish's result without checking for None, a str taken from price, a key that does not exist).

  2. Task 2

    totals.py: unions and None

    With type hints, so that mypy --strict totals.py finds no errors, write:

    parse_total(raw), where raw is an int or a str, returning the total as an int: 240, "240", "Rs 240", "₹240" and " Rs 1200 " are all valid;

    apply_coupon(total, coupon), where total is an int and coupon a str or None, returning the total after the coupon as an int. DABBA10 takes off 10% in whole rupees (the total minus total // 10, so 95 becomes 86), FIRST50 takes off 50 but never below 0, None or an empty string changes nothing, and any other coupon raises ValueError.

    The check also runs mypy on code that passes a float to parse_total or a number as the coupon: both must be errors.

  3. Task 3 · interview question

    Interview: group_by.py, a generic group_by

    Write group_by(items, key): items is any iterable, key is a function taking one item. It returns a dict from each key(item) to the list of the items with that key, in the order they came, the keys in the order they first appeared. group_by(["roti", "chole", "dal", "naan"], len) returns {4: ["roti", "naan"], 5: ["chole"], 3: ["dal"]}.

    The hints must be generic: mypy --strict finds no errors, accepts that result as a dict[int, list[str]], and rejects it as a dict[str, list[str]] or a dict[int, list[int]]. A key that is not a function must be an error too.

  4. Task 4

    fix_me.py: what mypy found

    fix_me.py has three bugs, and mypy --strict fix_me.py finds all three before the code runs. Fix the code (not the hints) until mypy says Success and the functions do what their docstrings say:

    rider_name(riders, R99) raises KeyError;

    label(rider, 12) returns the rider's name then (12 orders), like Santosh Kamble (12 orders);

    area_of(riders, None) returns unassigned, and area_of(riders, r2) returns R2's area, whatever the case of the id.

    No type: ignore comments and no Any.

What you will learn

  • Annotations: hints on variables, parameters and return values, and what they do (and do not do) at run time.
  • Containers and TypedDict: list[str], dict[str, int], and the shape of a JSON object.
  • None and unions: X | None, int | str, and narrowing.
  • Generics and Callable: functions whose types follow their input.
  • mypy in practice: --strict, reading its errors, Any.

More in Pythonic and typed

Build "Type hints" yourself

DabbaDrop, a Mumbai tiffin startup, runs on Excel and WhatsApp. You are its first Python developer. A real editor and terminal in your browser, AI that explains, and a Check that says when it works.

The first 2 chapters of Python, properly are free. This one comes with the all labs plan.