typing

Type annotations: a description of what values a function expects and what it returns. Checked by editors and tools such as mypy.

On this page

Example

#
Python
def average(scores: list[int]) -> float:
    return sum(scores) / len(scores)

def find_points(ranking: dict[str, int], name: str) -> int | None:
    return ranking.get(name)

ranking: dict[str, int] = {"Emma": 250, "Jack": 80}

print(average([80, 90, 100]))
print(find_points(ranking, "Emma"))
print(find_points(ranking, "Mia"))
print(average([1.5, 2.5]))
Resultsaved result, you can check it
90.0
250
None
2.0

The last call passes floating-point numbers, even though the annotation says list[int]. Python will run it without an error, and mypy would report a type mismatch.

Definition and usage

#

Type annotations are a description added to code: def award(name: str, exp: int = 10) -> str: says the function takes a string and a number, and returns a string. Python does not check them while the program runs. They are used by editors, which suggest code and underline errors, and by tools such as mypy or pyright, which catch mistakes before you run the program.

Collection types are written with built-in names and square brackets: list[int], dict[str, int], tuple[int, int]. A value of one of several types is described by the | operator, e.g. int | str, and str | None means a string or None. These are the newer forms of the Union[int, str] and Optional[str] notations from the typing module, which you will still meet in older code.

The typing module also provides tools for more complex cases. TypedDict describes a dictionary with fixed keys, e.g. a record read from JSON. Protocol specifies which methods an object must have, without requiring inheritance, so tools can check duck typing before the program runs. Literal narrows values to the listed ones, and Any turns checking off.

Annotations are also available while the program runs, which @dataclass, pydantic, and FastAPI make use of. You do not have to type everything at once: start with the parameters and results of functions, because tools can usually infer the types of local variables themselves.

Syntax

#
Syntax
from typing import Literal, Protocol, TypedDict

def function(parameter: type, optional: type | None = None) -> result_type:
    ...

variable: dict[str, int] = {}

The most common notations

#
  • list[int]

    Python 3.9

    A list of integers. set[str], tuple[int, str], and dict[str, int] (the type of keys and values) are written the same way.
  • int | str

    Python 3.10

    One of several types. The older notation: Union[int, str].
  • str | None

    Python 3.10

    A string or None. The older notation: Optional[str].
  • Literal[...]

    Python 3.8

    Only the listed values, e.g. Literal["easy", "hard"].
  • TypedDict

    Python 3.8

    A dictionary with fixed keys and value types.
  • Protocol

    Python 3.8

    A set of methods an object must have, without requiring inheritance.
  • Callable[[int], str]

    Python 3.5

    A function that takes an int and returns a str. Imported from collections.abc or typing.
  • Any

    Python 3.5

    Any type. Turns off checking for a given value.
  • type Alias = ...

    Python 3.12

    A named type alias, e.g. type Scores = list[int].

More examples

#
TypedDict: a dictionary with known keys
Python
from typing import NotRequired, TypedDict

class StudentData(TypedDict):
    name: str
    world: int
    badges: list[str]
    mentor: NotRequired[str]

def describe(student: StudentData) -> str:
    mentor = student.get("mentor", "none")
    return f"{student['name']} (world {student['world']}), mentor: {mentor}"

emma: StudentData = {"name": "Emma", "world": 7, "badges": ["Start"]}
print(describe(emma))
print(type(emma).__name__)
Resultsaved result, you can check it
Emma (world 7), mentor: none
dict

While the program runs, it is an ordinary dictionary. NotRequired marks a key that may be missing.

Protocol: required methods without inheritance
Python
from typing import Protocol

class Scorable(Protocol):
    def score(self) -> int: ...

class Quiz:
    def __init__(self, correct: int) -> None:
        self.correct = correct

    def score(self) -> int:
        return self.correct * 10

class Project:
    def score(self) -> int:
        return 50

def total(items: list[Scorable]) -> int:
    return sum(item.score() for item in items)

print(total([Quiz(3), Project(), Quiz(1)]))
Resultsaved result, you can check it
90

Quiz and Project do not inherit from Scorable, but they have a score() method, so type-checking tools will accept them.

Union, Optional, and Literal
Python
from typing import Literal, Optional, Union

Difficulty = Literal["easy", "medium", "hard"]

def exp_for(difficulty: Difficulty) -> int:
    return {"easy": 5, "medium": 10, "hard": 20}[difficulty]

def parse_points(value: Union[int, str]) -> Optional[int]:
    if isinstance(value, int):
        return value
    return int(value) if value.isdigit() else None

print(exp_for("hard"))
print(parse_points(40), parse_points("75"), parse_points("many"))
Resultsaved result, you can check it
20
40 75 None

In new code, Union[int, str] is written as int | str, and Optional[int] as int | None.

Good practices

#
  • Annotations will not stop bad data while the program runs. Run mypy or pyright, e.g. in your editor, and validate external data separately.
  • In new code, write list[int] and int | None instead of List[int] and Optional[int] from the typing module. The older notations still work.
  • Name a complex type that repeats in many places with an alias: type Ranking = dict[str, int] since Python 3.12, and in older versions with a plain assignment Ranking = dict[str, int].

Related entries

#

Practise it in lessons

#

Spotted a mistake or missing an example? Write to us.