Python Type Hints
Python is dynamically typed: variables don't have declared types. Since Python 3.5, though, you can add optional type hints (annotations) that say what types you expect. Python itself ignores them at runtime, but editors use them for autocompletion and error highlighting, and tools such as mypy and pyright use them to find bugs before your code runs.
Annotating functions and variables
Put : type after a parameter or variable and -> type after the parameter list for the return value:
def greet(name: str, times: int = 1) -> str:
return ", ".join([f"Hello {name}"] * times)
count: int = 3
ratio: float = 0.5
print(greet("Quyen", 2))
print(greet.__annotations__)Hello Quyen, Hello Quyen
{'name': <class 'str'>, 'times': <class 'int'>, 'return': <class 'str'>}
The hints are stored in __annotations__, but nothing checks them while the program runs:
def double(n: int) -> int:
return n * 2
print(double("ha")) # no error at runtime - a type checker would complainhaha
Note: Type hints are documentation that tools can verify. To actually enforce types at runtime you'd use
isinstancechecks or a library such as pydantic.
Collection types
Since Python 3.9 you can use the built-in collection types directly with square brackets:
| Hint | Means |
|---|---|
list[int] |
a list of ints |
dict[str, float] |
dict with str keys and float values |
tuple[int, int] |
a tuple of exactly two ints |
tuple[str, ...] |
a tuple of any number of strs |
set[str] |
a set of strings |
def average(scores: list[float]) -> float:
return sum(scores) / len(scores)
def word_lengths(words: list[str]) -> dict[str, int]:
return {w: len(w) for w in words}
def bounds(values: list[int]) -> tuple[int, int]:
return min(values), max(values)
print(average([7.5, 9.0, 8.5]))
print(word_lengths(["sun", "river"]))
print(bounds([4, 1, 9]))8.333333333333334
{'sun': 3, 'river': 5}
(1, 9)
Optional values and unions
When a value may be one of several types, use | (Python 3.10+). X | None means "an X or nothing" — very common for results that might be missing:
def find_user(user_id: int) -> str | None:
users = {1: "Ha", 2: "Kien"}
return users.get(user_id)
def parse(value: int | str) -> int:
return value if isinstance(value, int) else int(value)
print(find_user(2), find_user(9))
print(parse(5) + parse("7"))Kien None
12
On Python 3.9 and earlier, write Optional[str] and Union[int, str] from the typing module instead.
The typing module
| Tool | Use |
|---|---|
Any |
opt out of checking for one value |
Callable[[int, int], int] |
a function taking two ints, returning int |
Iterable[str], Iterator[int] |
anything you can loop over |
TypeAlias / simple assignment |
give a long type a name |
TypedDict |
a dict with fixed keys and value types |
Protocol |
"any object with these methods" (duck typing) |
Literal["r", "w"] |
only these exact values |
from typing import Callable, Iterable, TypedDict
Vector = list[float] # a type alias
def scale(v: Vector, k: float) -> Vector:
return [x * k for x in v]
def apply(op: Callable[[int, int], int], a: int, b: int) -> int:
return op(a, b)
def total(items: Iterable[int]) -> int:
return sum(items)
class Movie(TypedDict):
title: str
year: int
m: Movie = {"title": "Spirited Away", "year": 2001}
print(scale([1.0, 2.5], 2))
print(apply(lambda x, y: x * y, 6, 7))
print(total(range(5)), total({1, 2}))
print(m["title"], m["year"])[2.0, 5.0]
42
10 3
Spirited Away 2001
Hints on classes
Type hints work naturally with your own classes and are what make dataclasses so concise:
from dataclasses import dataclass
@dataclass
class Task:
title: str
done: bool = False
def pending(tasks: list[Task]) -> list[str]:
return [t.title for t in tasks if not t.done]
todo = [Task("write tests"), Task("fix bug", done=True), Task("deploy")]
print(pending(todo))['write tests', 'deploy']
Checking hints with mypy
A type checker reads your code without running it. After pip install mypy, it finds mistakes like the double("ha") call above:
mypy app.pyapp.py:4: error: Argument 1 to "double" has incompatible type "str"; expected "int" [arg-type]
Found 1 error in 1 file (checked 1 source file)
Tip: Add hints gradually — start with function signatures in the code you share with others. Even partial hints make editors much more helpful.
Test yourself
What happens at runtime if you pass a str to a parameter hinted as int?
- TypeError is raised
- The value is converted to int
- Nothing - hints are not enforced at runtime
- A warning is printed
Which hint means "a string or None" in Python 3.10+?
- str?
- str | None
- Optional(str)
- str or None
How do you annotate a function's return type?
- def f() : int
- def f() -> int:
- def f() returns int:
- int def f():