Python Type Hints
In this page:
def function_name(parameter: type) -> return_type:
# body
variable: type = value
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: # hints document expected types, ignored at runtime
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: # name must be a str, function returns a 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 # type hint documents this as a float
is_active: bool = True # type hint documents this as a bool
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"] # a list of strings
ages: Dict[str, int] = {"Alex": 30} # a dict mapping strings to ints
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))
- Expecting type hints to be enforced at runtime, when Python ignores them and
add("a", "b")still runs. - Writing
list[int]on very old Python versions before 3.9, which raisesTypeError; usetyping.List[int]there. - Returning a value that does not match the hint, such as
-> inton a function that returns a string, which only a checker such as mypy will report.
Chapter Quiz — Complete all 12 topics to unlock
0/12 topics done
Complete these topics first: