Python Type Hints
In this page:
What are Type Hints?
Type hints, introduced in Python 3.5 via PEP 484, are annotations that document a variable's or parameter's expected type without changing how the code actually runs -- Python's interpreter still ignores them at runtime. Their real value is upfront: editors and IDEs use them for accurate autocomplete, and static checkers use them to catch type mistakes before you ever run the code.
Example: What are Type Hints?
def add(a: int, b: int) -> int:
return a + b
print(add(2, 3))
Function Parameter Type Hints
Annotating a function signature means writing param: Type for each parameter and -> ReturnType right before the closing colon of the def line. This makes a function's contract explicit at a glance, without needing to read its implementation or docstring to know what it expects and returns.
Example: Function Parameter Type Hints
def greet(name: str) -> str:
return f"Hello, {name}"
print(greet("Alex"))
Type Hinting Floating-Point Variables
Simple scalar hints like float or bool are the easiest place to start, since they document intent for values that would otherwise be ambiguous from a bare variable name alone. They cost nothing at runtime and immediately make numeric or flag-like variables self-explanatory to anyone reading the code later.
Example: Type Hinting Floating-Point Variables
price: float = 19.99
is_active: bool = True
print(price, is_active)
Complex Types from typing Module
For anything beyond simple scalars -- lists, dicts, tuples, or unions of several types -- you import generic types like List, Dict, and Tuple from the typing module (or use built-in generics directly in Python 3.9+, e.g. list[int]). This lets you express structured shapes like 'a list of strings' or 'a dict mapping names to ages' precisely.
Example: Complex Types from typing Module
from typing import List, Dict
names: List[str] = ["Alex", "Sam"]
ages: Dict[str, int] = {"Alex": 30}
print(names, ages)
Benefits of Type Hints
Tools like mypy read your type hints and statically analyze your codebase for type mismatches -- passing a string where an int is expected, for instance -- without ever running the program. Catching these errors before deployment is especially valuable in larger codebases where a wrong type can silently propagate for a long time before it causes a visible bug.
Example: Benefits of Type Hints
def add(a: int, b: int) -> int:
return a + b
# A type checker like mypy would flag this at analysis time:
# add("2", 3)
print(add(2, 3))
Chapter Quiz — Complete all 12 topics to unlock
0/12 topics done
Complete these topics first: