Advanced   Chapter 147 · 30 min read · Module 11: Advanced Python

Type Hints

Learning objectives
  • After this chapter you can add type hints to parameters, return values and variables.
  • You can describe lists, dictionaries and tuples with built-in generic types.
  • You can write unions and optional values with the | operator.
  • You can explain that hints are not enforced at run time and how a type checker uses them.
  • You can write a simple generic function with TypeVar.

Python is a dynamically typed language, which means a variable can hold any kind of value and the type is checked only when the code runs. This is flexible, but in big programs it can make code hard to understand. When you read def send(a, b) you cannot tell what a and b should be. Type hints solve this problem by letting you write the expected types next to the names.

A type hint is a label, not a rule. Python itself does not stop you from passing the wrong type. Instead, the hints are read by people, by editors that give you better auto-complete, and by tools such as mypy and pyright that find mistakes before you run the program. Because hints cost almost nothing at run time, many professional projects use them everywhere.

In this chapter you will learn to hint function parameters, return values and variables, to describe lists, dictionaries and tuples, to say that a value may be missing, and to write generic functions. You will also see what Python really does with hints when the program runs.

Hinting functions and variables

To hint a parameter, write a colon and a type after its name. To hint the return value, write -> and a type before the final colon. A variable can be hinted with a colon after the name, with or without a value. If a function returns nothing useful, its return type is None.

Example 1: basic hints
def area(width: float, height: float) -> float:
    return width * height

def greet(name: str) -> None:
    print('Hello,', name)

count: int = 3
label: str
print(area(2.5, 4))
greet('Mia')
print(count)
10.0 Hello, Mia 3

Notice that label: str only declares a hint. No value is created, so reading label before assigning it would raise a NameError. A hint never creates a variable by itself.

Hints are not enforced

This is the most important fact about type hints. Python stores them but never checks them while the program runs. If you pass a string to a function that says it wants an integer, Python will still try to run it. The stored hints can be seen in the __annotations__ attribute of a function, which is how tools and libraries read them.

Example 2: hints are only information
def double(n: int) -> int:
    return n * 2

print(double(4))
print(double('ab'))
print(double.__annotations__)
8 abab {'n': <class 'int'>, 'return': <class 'int'>}
Static type checker: a separate tool, such as mypy, that reads your hints and reports type mistakes without running the program

Collections and unions

Since Python 3.9 you can use the built-in names list, dict, set and tuple with square brackets to describe what is inside: list[int] is a list of integers and dict[str, float] is a dictionary with text keys and decimal values. A tuple with a fixed shape lists every position, such as tuple[str, int], while tuple[int, ...] means any number of integers. Older code imports List and Dict from the typing module, but the built-in versions are now preferred.

When a value can be one of several types, use the pipe symbol. Python 3.10 allows int | str, which replaces the older Union[int, str]. A value that may be missing is written str | None, which replaces Optional[str]. Type checkers will then remind you to check for None before using the value.

Example 3: lists, dicts and unions
def average(scores: list[int]) -> float:
    return sum(scores) / len(scores)

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

print(average([80, 90, 100]))
ages = {'Ravi': 30}
print(find_age(ages, 'Ravi'))
print(find_age(ages, 'Zoe'))

def show(value: int | str) -> str:
    return f'value={value}'
print(show(5), show('x'))
90.0 30 None value=5 value=x

Callables, Any and aliases

Functions can be passed around too. Callable[[int, int], int] from collections.abc describes a function that takes two integers and returns an integer. Any from the typing module means any type at all and turns off checking for that value. You can also give a long type a short name, called a type alias, with a simple assignment such as Point = tuple[float, float].

Example 4: Callable and alias
from collections.abc import Callable

Point = tuple[float, float]

def apply(op: Callable[[int, int], int], a: int, b: int) -> int:
    return op(a, b)

def distance_from_origin(p: Point) -> float:
    return (p[0] ** 2 + p[1] ** 2) ** 0.5

print(apply(lambda x, y: x + y, 3, 4))
print(distance_from_origin((3.0, 4.0)))
7 5.0

Generics with TypeVar

Sometimes the output type depends on the input type. A function that returns the first item of a list should give back an int for a list of integers and a str for a list of strings. A TypeVar is a placeholder type that links the input and the output. Python 3.12 added a shorter syntax, def first[T](items: list[T]) -> T:, but the classic TypeVar form below works on all Python 3 versions.

Example 5: a generic function
from typing import TypeVar

T = TypeVar('T')

def first(items: list[T]) -> T:
    return items[0]

print(first([10, 20, 30]))
print(first(['a', 'b']))
10 a

Checking hints with a tool

To get real value from hints you run a checker. Install mypy with pip and run it on your file. It reads every hint and reports where a call or return does not match. The command line is mypy program.py. Because installing tools is outside this lesson, the sample below only shows what a typical report looks like.

Example 6: a typical mypy report
def add(a: int, b: int) -> int:
    return a + b

add('1', 2)
program.py:4: error: Argument 1 to "add" has incompatible type "str"; expected "int"
Start by hinting function signatures. They give the most benefit. Hints for local variables are often optional because checkers can work them out.

Python syntax

Syntax
def name(param: type, other: type = default) -> return_type:
Syntax
variable: type = value
Syntax
list[int]   dict[str, float]   tuple[str, int]   set[str]
Syntax
int | str   str | None
Syntax
Callable[[int, int], int]
Syntax
T = TypeVar('T')

Real-world applications

  • Making large codebases easier to read and maintain.
  • Getting better auto-complete and error hints in editors.
  • Catching bugs before running code with mypy or pyright.
  • Documenting function inputs and outputs for teammates.
  • Libraries such as dataclasses and FastAPI that read hints.

Common mistakes

Mistake: Believing that Python raises an error when a wrong type is passed.
Fix: Hints are not enforced. Use a type checker or explicit isinstance checks if you need a guarantee.
Mistake: Using a mutable default such as def f(items: list[int] = []).
Fix: Hints do not change default behaviour. Use None as the default and create the list inside the function.
Mistake: Forgetting that str | None must be checked for None before use.
Fix: Write if value is not None: before calling string methods on it.
Mistake: Writing list(int) instead of list[int] in a hint.
Fix: Use square brackets for the item type.
Mistake: Using X | Y unions on Python older than 3.10.
Fix: Use Union[X, Y] from typing, or upgrade Python.

Important tips

  • Hint function signatures first and variables later.
  • Use X | None instead of Optional in new code.
  • Prefer built-in list, dict and tuple over typing.List and typing.Dict.
  • Use type aliases to give long types a meaningful name.
  • Run mypy in your editor or in automated tests.

Key points summary

  • A hint is information, not a rule.
  • The return hint uses -> and None means nothing is returned.
  • Hints are stored in __annotations__.
  • list[int] and dict[str, int] describe contents.
  • The | operator joins types from Python 3.10.
  • TypeVar links input and output types in generic functions.

Exam and interview points

  • Hints are not checked at run time by Python.
  • Know the syntax for return annotations.
  • list[int] works from Python 3.9, int | str from 3.10.
  • Optional[X] equals X | None.
  • Function annotations live in __annotations__.

Quick revision

  • def f(x: int) -> str: ...
  • Python does not enforce hints.
  • list[int], dict[str, int], tuple[int, ...].
  • int | None means optional.
  • TypeVar makes generic functions.
  • mypy checks hints before running.

Frequently asked questions

Do type hints make my program faster?

No. Python ignores them while running, so speed does not change. The benefit is clearer code and fewer bugs.

Are type hints required?

No, they are optional. You can add them slowly, one function at a time.

What is the difference between Optional[str] and str | None?

They mean the same thing. The pipe form is shorter and is available from Python 3.10.

What does Any mean?

Any says a value can be of any type and the checker will not complain about it. Use it rarely because it removes the safety of hints.

Practise this chapter

17 practice questions Take the chapter quiz

Related chapters