Python is a dynamically typed language: a variable can hold a number and, later, a text. Type annotations (*type hints*) let you indicate which type is expected, so that the code is easier to understand.
Annotating variables
name: str = "Ana"
age: int = 30
height: float = 1.68
active: bool = True
print(name, age, height, active) # Ana 30 1.68 True
It is written variable: type = value. It is optional: Python works the same without them.
Annotating functions
In a function you annotate the type of each parameter and the type of what it returns, after an arrow ->:
def rectangle_area(base: float, height: float) -> float:
return base * height
print(rectangle_area(3, 4.5)) # 13.5
A function that returns nothing is annotated with -> None:
def greet(name: str) -> None:
print(f"Hello, {name}")
greet("Ana") # Hello, Ana
Collections
You indicate the type of the container and, in square brackets, the type of its elements:
| Annotation | Means |
|---|---|
list[int] | A list of integers |
dict[str, int] | A dictionary with text keys and integer values |
tuple[int, str] | A tuple of two elements: an integer and a text |
set[str] | A set of texts |
def statistics(numbers: list[int]) -> dict[str, int]:
return {"min": min(numbers), "max": max(numbers), "sum": sum(numbers)}
print(statistics([4, 8, 15])) # {'min': 4, 'max': 15, 'sum': 27}
Practice with Statistics with types.
Optional values
If a value can be of one type or None, use |:
def search(items: list[int], target: int) -> int | None:
for i, value in enumerate(items):
if value == target:
return i
return None
print(search([5, 8, 2], 8)) # 1
print(search([5, 8, 2], 9)) # None
Annotations are NOT checked
This is the most important point: Python does not force them to be met when running. They are a hint for people and for tools:
def double(x: int) -> int:
return x * 2
print(double(21)) # 42
print(double("ab")) # abab (no error, even though it is not an int)
Programs such as mypy, or editors such as VS Code and PyCharm, read the annotations and warn about errors *before* running. Python stores the annotations and they can be consulted:
print(double.__annotations__)
# {'x': <class 'int'>, 'return': <class 'int'>}
What are they for?
- They document: you see at a glance what a function expects and returns.
- They catch errors before running, with the help of an editor or mypy.
- Smarter autocompletion in the editor.
- They are the basis of tools such as dataclasses, which we will see next.