Course map
Stage 1: Foundation
Stage 2: Intermediate
Stage 3: Advanced
Stage 4: DSA in Python
Stage 5: Specialization

Part 11 / Topic 9 of 12

Type hints in depth

In Part 5 you wrote simple hints like price: float. A type hint says what type a value should be. Python does not check hints when it runs; tools like mypy and your editor do. Like labels on kitchen jars: the jar still holds whatever you put in, but the label stops you from adding salt to the tea.

Built-in generics

A generic type says what is inside a container.

names: list[str] = ["Asha", "Ravi"]
prices: dict[str, float] = {"Pen": 20.0, "Bag": 499.0}
point: tuple[str, int] = ("Pune", 411001)      # fixed length: a str, then an int
cities: set[str] = {"Pune", "Delhi"}
print(prices["Bag"])                           # 499.0

X | None: "this, or nothing"

def find_price(prices: dict[str, float], name: str) -> float | None:
    return prices.get(name)                    # None when the name is missing

print(find_price({"Pen": 20.0}, "Pen"))        # 20.0
print(find_price({"Pen": 20.0}, "Laptop"))     # None

Callable: a function as a value

Callable[[float], float] means "a function that takes one float and returns a float" (functions as values, Part 5).

from collections.abc import Callable

def apply_to_all(prices: list[float], rule: Callable[[float], float]) -> list[float]:
    return [round(rule(price), 2) for price in prices]

print(apply_to_all([1200.0, 350.0], lambda p: p * 0.8))   # [960.0, 280.0]

TypedDict (brief)

A TypedDict describes a dict with fixed keys and a type for each key. At runtime it is a normal dict.

from typing import TypedDict

class Product(TypedDict):
    name: str
    price: float

kurta: Product = {"name": "Kurta", "price": 1200.0}
print(kurta["price"])                          # 1200.0

For real objects with behaviour, prefer a class or a dataclass (Part 9).

Running mypy

python -m pip install mypy
mypy examples/06_type_hints_tour.py     # check one file
mypy examples/                          # check a folder

If you write find_price({"Pen": 20.0}, "Pen") + 5, mypy warns you that the result might be None:

bad.py:5: error: Unsupported operand types for + ("None" and "int")  [operator]
bad.py:5: note: Left operand is of type "float | None"
Found 1 error in 1 file (checked 1 source file)

All code in this part passes mypy. Full tour: 06_type_hints_tour.py.

๐Ÿ” Going deeper: generics you write yourself (TypeVar, class Box[T]), Protocol and strict mypy settings are coming in Stage 3.

Read more: the official typing documentation.

Done here? The practice set for Part 11 โ€” 7 exercises with solutions โ€” is on the part page.

Search the guide