Type hints and static checking
Annotate functions and variables with types, describe collections, optional values and your own classes, and check them with mypy.
In this lesson you will
- Annotate parameters and return values
- Describe lists, dicts and optional values
- Use Callable, TypedDict and Literal
- Run mypy to catch mistakes
About 21 minutes
Labels that make code self-explanatory
You open a function written six months ago: def process(data, flag):. What is data: a list, a dictionary, a filename? What does it return? You have to read the whole body to find out. Type hints are small labels that answer those questions right in the code. Python does not enforce them when running, but your editor uses them to autocomplete and warn you, and tools like mypy check them for you. Large codebases rely on them heavily.
The basics
def greet(name: str, times: int = 1) -> str:
return (f"Hello, {name}! " * times).strip()
age: int = 30
price: float = 19.99
active: bool = True
tags: list[str] = ["python", "typing"]
scores: dict[str, int] = {"Sara": 90, "Ali": 72}
print(greet("Sara", 2))
print(greet.__annotations__)
Hello, Sara! Hello, Sara!
{'name': <class 'str'>, 'times': <class 'int'>, 'return': <class 'str'>}
name: str says “this should be text”. -> str says “this returns text”. The hints are stored in __annotations__ and otherwise ignored when the program runs.
Python really does not check them. greet(5) would still run. The value comes from editors and checkers catching the mistake before you run the program.
def double(x: int) -> int:
return x * 2
print(double("ha")) # Python happily runs this: hints are not enforced
haha
Collections, optional values and unions
from typing import Optional
def find_user(users: dict[int, str], user_id: int) -> Optional[str]:
return users.get(user_id) # a str, or None
def average(numbers: list[float]) -> float:
return sum(numbers) / len(numbers)
def to_number(value: int | str) -> int: # either type is fine
return int(value)
users = {1: "Sara"}
print(find_user(users, 1), find_user(users, 9))
print(average([1.5, 2.5]), to_number("42"), to_number(7))
Sara None
2.0 42 7
| Hint | Meaning |
|---|---|
list[int] |
A list of integers |
dict[str, float] |
Keys are text, values are decimals |
tuple[int, str] |
Exactly an int then a str |
set[str] |
A set of text |
int | None or Optional[int] |
An int or nothing |
int | str |
Either type |
Any |
No restriction (use sparingly) |
Callable[[int], str] |
A function taking an int and returning text |
Your own types
from dataclasses import dataclass
from typing import Callable
@dataclass
class Product:
name: str
price: float
def total(items: list[Product]) -> float:
return sum(p.price for p in items)
def apply(items: list[Product], rule: Callable[[float], float]) -> list[Product]:
return [Product(p.name, rule(p.price)) for p in items]
shop = [Product("Pen", 50), Product("Bag", 1200)]
print(total(shop))
print(apply(shop, lambda price: price * 0.9))
1250
[Product(name='Pen', price=45.0), Product(name='Bag', price=1080.0)]
Type aliases, TypedDict and Literal
from typing import TypedDict, Literal
Row = dict[str, str] # an alias gives a long type a short name
class UserInfo(TypedDict):
name: str
age: int
Mode = Literal["read", "write"]
def open_file(path: str, mode: Mode) -> str:
return f"opened {path} for {mode}"
user: UserInfo = {"name": "Sara", "age": 21}
print(user["name"], open_file("a.txt", "read"))
Sara opened a.txt for read
Generics: one function, many types
from typing import TypeVar
T = TypeVar("T")
def first(items: list[T]) -> T:
return items[0]
print(first([10, 20, 30]), first(["a", "b"]))
10 a
Checking hints with mypy
Install the checker with pip install mypy, then run it on your file. Here a deliberate mistake is caught without running the program. The output below is what mypy typically prints; it is shown as an example rather than run output.
def double(x: int) -> int:
return x * 2
result: str = double("ha")
$ python -m mypy app.py
app.py:4: error: Argument 1 to "double" has incompatible type "str"; expected "int" [arg-type]
app.py:4: error: Incompatible types in assignment (expression has type "int", variable has type "str") [assignment]
Found 2 errors in 1 file (checked 1 source file)
Believing hints protect you at runtime. They do not: if user input arrives as text, you still need to convert and validate it. Use hints for documentation and checking during development, and keep your try/except for real data.
You do not have to annotate everything. Start with function signatures (parameters and return types), the part that gives the biggest clarity for the least effort, and let your editor guide you from there.
Add type hints to this function and a one-line docstring: def total_price(prices, tax) returns the sum of the prices times (1 + tax).
Show one possible answer
def total_price(prices: list[float], tax: float) -> float:
"""Return the sum of prices including tax."""
return sum(prices) * (1 + tax)
print(total_price([100.0, 50.0], 0.1))
165.0
Write a function longest(words: list[str]) -> str | None that returns the longest word, or None for an empty list.
Hint: Handle the empty list first.
Show one possible answer
def longest(words: list[str]) -> str | None:
if not words:
return None
return max(words, key=len)
print(longest(["tea", "coffee", "milk"]))
print(longest([]))
coffee
None
Worked example: typing a small inventory module
Let us see hints earn their keep in a realistic module. Read the signatures alone, without the bodies: they already tell you what goes in and what comes out. That is the point of hints. A new teammate can use these functions without reading a single line of the implementation.
from dataclasses import dataclass, field
from typing import Optional
@dataclass
class Item:
sku: str
name: str
price: float
stock: int = 0
tags: list[str] = field(default_factory=list)
class Inventory:
def __init__(self) -> None:
self._items: dict[str, Item] = {}
def add(self, item: Item) -> None:
self._items[item.sku] = item
def find(self, sku: str) -> Optional[Item]:
return self._items.get(sku)
def low_stock(self, limit: int = 5) -> list[Item]:
return [i for i in self._items.values() if i.stock <= limit]
def total_value(self) -> float:
return sum(i.price * i.stock for i in self._items.values())
inv = Inventory()
inv.add(Item("P1", "Pen", 45.0, 120, ["stationery"]))
inv.add(Item("B1", "Bag", 1250.0, 3))
print(inv.find("P1").name)
print(inv.find("ZZ"))
print([i.name for i in inv.low_stock()])
print(inv.total_value())
Pen
None
['Bag']
9150.0
Notice find returns Optional[Item]. That tells every caller: “this might be None, so check before using it.” Without the hint, forgetting that check would crash the program months later with AttributeError: 'NoneType' object has no attribute 'name'. A checker such as mypy flags the unsafe call immediately.
A good signature such as def find(self, sku: str) -> Optional[Item] replaces a paragraph of comments, and unlike comments it can be checked, so it cannot quietly go out of date.
Check what you learned
Five quick questions. Pick an answer and you will see straight away whether it is right and why.
Does Python enforce type hints while running?
- Yes always
- No, they are not enforced
- Only for int
- Only in functions
Tools like mypy check them separately.
What does -> str mean in a function definition?
- It takes text
- It prints text
- It is a comment
- The function returns text
-> declares the return type.
What does int | None mean?
- Two integers
- An integer or nothing
- Integer division
- An error
A union of two types.
Which tool checks hints without running the code?
- pip
- venv
- json
- mypy
mypy is a static type checker.
What is the purpose of TypeVar?
- To say the output type matches the input type
- To create variables
- To delete types
- To print types
Generic functions keep track of the type.
Summary
- Hints document what code expects.
- Python does not enforce them; mypy and editors do.
- Use list[int], dict[str, int], int | None.
- Start with function signatures.
Questions
Do type hints make code faster?
No. They are for people and tools, not for speed.
Should I use Optional or / None?
Both mean the same. The | None form is shorter in modern Python.
Are hints required?
No, but most professional projects use them for clarity and early bug detection.
