Skip to content
Tutorials Center
My learning

Topics

Lesson 84 of 149 ยท Beyond the Basics

Type Hints

Learn Python type hints - annotate variables and functions, use list[int], unions with |, Optional, TypedDict, Literal and generics, and check code with mypy.

Python is dynamically typed: a variable can hold any kind of value, and nothing stops you from passing a string where a function expects a number. That flexibility is pleasant in small scripts, but in bigger programs it lets mistakes slip through until the exact line runs, sometimes in production.

Type hints (also called type annotations) let you write down what types you expect: def total(prices: list[float]) -> float:. Python itself doesn't enforce them at runtime. Instead, they help three audiences: readers, who see at a glance what a function takes and returns; editors, which use them for autocomplete and inline warnings; and type checkers such as mypy, which scan your code and report mismatches before you run it. You've already seen hints throughout the Object-Oriented Programming lessons; this lesson explains them properly.

Annotating functions and variables

Put : type after a parameter or variable name, and -> type before the colon of a def for the return type:

Python Basic annotations

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The last line passes an int where a str is expected, and Python runs it anyway because f-strings accept anything. A type checker would flag that call. The annotations are simply stored on the function (__annotations__) for tools to read.

Note: Use -> None for functions that don't return a value. It tells readers and checkers that using the result, such as x = log("hi"), is probably a mistake.

Built-in types and collections

For simple values, use the type itself: int, float, str, bool, bytes. For collections, put the item types in square brackets:

Hint Meaning
list[int] a list of ints
set[str] a set of strings
dict[str, float] a dict with string keys and float values
tuple[int, str] exactly two items: an int, then a str
tuple[int, ...] any number of ints
Python Collection hints

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Older code imports List, Dict and Tuple from typing (with capital letters). Since Python 3.9 the built-in names work directly, so prefer list[int] over List[int].

When a function only reads its argument, a more general hint from collections.abc makes it more flexible. Iterable[str] accepts lists, tuples, sets and generators; Sequence[str] accepts anything indexable such as lists and tuples; Mapping[str, int] accepts any read-only dict-like object.

Unions and Optional

When a value can be one of several types, join them with |. The most common case is "a value or None":

Python Unions and None

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

str | None is the same as Optional[str] from the typing module, which you'll see in older code. The | syntax works in Python 3.10 and later.

The if name is None check is called narrowing. Before it, name might be None, so calling name.upper() would be flagged. Inside the else branch, a checker knows it must be a str. isinstance() narrows the same way. This is one of the best things type hints do for you: they force you to handle the None case you might have forgotten.

Any, Literal and Callable

A few more tools from the typing and collections.abc modules come up often:

Python
from collections.abc import Callable
from typing import Any, Literal

def debug(value: Any) -> None: ...           # anything goes; checking is switched off

Mode = Literal["r", "w", "a"]                  # only these exact values
def open_log(mode: Mode) -> None: ...

def apply(func: Callable[[int, int], int], a: int, b: int) -> int:
    return func(a, b)                          # a function taking two ints, returning an int

Use Any sparingly: it tells the checker to trust everything about that value, which also means it can't help you. object is the stricter alternative for "any type, but I'll check before using it".

TypedDict for dictionary shapes

dict[str, Any] says nothing about which keys exist. When dictionaries have a fixed shape, as with JSON data, a TypedDict describes each key and its type:

Python TypedDict

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

At runtime a TypedDict is just a normal dict, as the last line shows. The benefit is entirely for the checker: misspell movie["titel"] and mypy reports it. NotRequired marks keys that may be missing. If you're designing your own data rather than describing existing dictionaries, a data class is usually the better choice.

Type aliases and generics

A type alias gives a long hint a short name. Python 3.12 added the type statement for this:

Python
type Point = tuple[float, float]
type Polygon = list[Point]

Generics let a function or class work with any type while keeping the types connected. In this function, whatever type the list holds, the return value has the same type. The [T] after the function name declares a type variable (Python 3.12+ syntax):

Python A generic function and class

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

A checker now knows that first([3, 1, 2], 0) returns an int and that tabs.pop() returns a str. Before 3.12 you'd write the same idea with T = TypeVar("T") and Generic[T], which you'll still see in many libraries.

Checking your code with a type checker

Type hints pay off when a tool reads them. The most widely used checkers are mypy and pyright (which powers type checking in VS Code's Python extension). They're installed with pip and run from the terminal, not in this browser runner, so here's what a session looks like:

Python
# shop.py
def total(prices: list[float]) -> float:
    return sum(prices)

total(["4.50", "3.20"])

Running mypy shop.py reports something like: error: List item 0 has incompatible type "str"; expected "float". You catch the bug without running the program. Many teams run a checker automatically on every commit.

Tip: You don't have to annotate everything at once. Type hints are optional and gradual: unannotated code is simply not checked. Start with function signatures in the most important modules; checkers infer the types of most local variables on their own.

Hints are also used at runtime by some libraries. Data classes read them to find fields, and frameworks such as Pydantic and FastAPI use them to validate and convert input data. In Python 3.14, annotations are evaluated lazily, only when something asks for them, so a class can refer to itself in its own hints (def merge(self, other: Color) -> Color) without the quotes older versions needed.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does Python do at runtime if you call def double(n: int) -> int with a string?

    Type hints are not checked when code runs. Tools like mypy find such mistakes ahead of time.
  2. 2. Which hint means "a string or None"?

    str | None (or the older Optional[str]) describes a value that is either a str or None.
  3. 3. How do you hint a dictionary that maps product names to prices?

    The first type in brackets is the key type, the second is the value type.
  4. 4. What is a TypedDict at runtime?

    TypedDict only describes the expected keys for type checkers. The actual objects are plain dictionaries.
  5. 5. In def first[T](items: list[T]) -> T, what does T do?

    T is a type variable: whatever the list holds, the return value has that same type.

Summary

  • Type hints annotate parameters (name: str), return values (-> int) and variables; Python stores them but doesn't enforce them.
  • Use built-in generics like list[int], dict[str, float] and tuple[int, ...].
  • Join alternatives with |; str | None is the modern spelling of Optional[str]. Checks like is None narrow the type.
  • Any, Literal, Callable and TypedDict cover common special cases.
  • Type aliases (type Point = ...) and generics (def first[T](...)) keep complex hints readable and connected.
  • Type checkers such as mypy and pyright read the hints and report bugs before you run your code.

Next: Async Programming with asyncio, where you'll run many waiting tasks at once with async and await.