Type hints are annotations that say what kind of value a variable, parameter or return value should hold, such as name: str or -> float. Python does not enforce them when the program runs, but editors and tools such as mypy use them to catch mistakes before you run the code, and they make functions self-documenting. This lesson covers the basic syntax and the most useful types from modern Python.
In this lesson you will learn
- Annotating parameters, return values and variables
- Built-in generic types:
list[int],dict[str, float],tuple - Optional values with
X | None Callable,LiteralandTypedDict- Type aliases and generic functions (Python 3.12+)
- Checking hints with a static type checker
Basic Annotations
def average(marks: list[float]) -> float:
return sum(marks) / len(marks)
def greet(name: str, times: int = 1) -> str:
return " ".join([f"Hi {name}!"] * times)
def find(names: list[str], target: str) -> int | None:
return names.index(target) if target in names else None
print(average([3.5, 3.9, 3.2]))
print(greet("Nadia", 2))
print(find(["a", "b"], "b"), find(["a", "b"], "z"))
scores: dict[str, int] = {"Rafi": 64, "Mitu": 91}
point: tuple[int, int] = (3, 4)
print(scores, point)
# Hints are not enforced at run time
print(greet(42)) # runs, though a checker would complain
print(average.__annotations__)
Output
3.533333333333333
Hi Nadia! Hi Nadia!
1 None
{'Rafi': 64, 'Mitu': 91} (3, 4)
Hi 42!
{'marks': list[float], 'return': <class 'float'>}
marks: list[float]says the parameter should be a list of floats, and-> floatgives the return type.- Since Python 3.9 the built-in types can be used directly:
list[str],dict[str, int],tuple[int, int]. Older code importsListandDictfromtyping. int | None(Python 3.10+) means “an int or None”. It is the same as the olderOptional[int].- Variables can be annotated too:
scores: dict[str, int] = {...}. - Hints are not checked at run time.
greet(42)runs happily even thoughnameshould be astr. Hints are stored in__annotations__and read by tools.
More Precise Types
from typing import Callable, TypedDict, Literal, Any
class Student(TypedDict):
name: str
cgpa: float
def best(students: list[Student]) -> Student:
return max(students, key=lambda s: s["cgpa"])
def apply(fn: Callable[[int], int], value: int) -> int:
return fn(value)
Mode = Literal["r", "w", "a"]
def open_mode(mode: Mode) -> str:
return {"r": "read", "w": "write", "a": "append"}[mode]
type Matrix = list[list[float]] # type alias (Python 3.12+)
def size(m: Matrix) -> tuple[int, int]:
return len(m), len(m[0])
def first[T](items: list[T]) -> T: # generic function (Python 3.12+)
return items[0]
print(best([{"name": "Tania", "cgpa": 3.95}, {"name": "Arif", "cgpa": 3.41}]))
print(apply(lambda n: n * n, 9))
print(open_mode("a"), size([[1.0, 2.0], [3.0, 4.0], [5.0, 6.0]]))
print(first(["x", "y"]), first([10, 20]))
Output
{'name': 'Tania', 'cgpa': 3.95}
81
append (3, 2)
x 10
TypedDictdescribes a dictionary with fixed keys and value types, which is common for JSON-like data.Callable[[int], int]describes a function that takes an int and returns an int, so you can type arguments such as callbacks and lambdas.Literal["r", "w", "a"]allows only those exact values; a checker flagsopen_mode("x").type Matrix = list[list[float]]creates a readable type alias.def first[T](items: list[T]) -> Tis a generic function: whatever type the list holds, the result has the same type.- Use
Anyonly when a value can truly be anything; it switches checking off for that value.
Checking Your Hints
python -m pip install mypy
mypy hints.py
For the greet(42) call above, mypy reports an error along the lines of: Argument 1 to “greet” has incompatible type “int”; expected “str”. Editors such as VS Code (with Pylance) show the same warnings as you type. Install tools inside a virtual environment.
| Hint | Meaning |
|---|---|
int, str, float, bool | Simple types |
list[int], set[str] | Collection of one element type |
dict[str, float] | Keys and values |
tuple[int, str], tuple[int, ...] | Fixed or variable length tuple |
X | None | X or None |
Callable[[A, B], R] | Function from A, B to R |
Common Mistakes
- Believing hints validate input; check data yourself or use a library such as pydantic.
- Using
list[int]on Python 3.8 or older, which raises an error; usetyping.Listthere. - Forgetting
| Noneon a function that can returnNone. - Overusing
Any, which hides the mistakes hints are meant to catch.
Practice Exercises
Exercise 1. Add type hints to def word_count(text): return len(text.split()).
Show answer
def word_count(text: str) -> int:
return len(text.split())
Exercise 2. Annotate a function that takes a dictionary of names to marks and returns the top name, or None if the dictionary is empty.
Show answer
def top(marks: dict[str, int]) -> str | None:
return max(marks, key=marks.get) if marks else None
Frequently Asked Questions
Do type hints make Python faster?
No. The standard interpreter ignores them when running code. Their value is in catching bugs early and documenting intent.
Do I have to annotate everything?
No. Hints are optional and can be added gradually. Start with public functions, where they help callers most.
Summary
- Write
param: typeand-> return_typeto annotate functions. - Use built-in generics like
list[int]and unions likestr | None. TypedDict,CallableandLiteraldescribe data precisely.- Python does not enforce hints; run mypy or rely on your editor to check them.
Next: Python Dataclasses.
