Skip to contentSkip to navigation

Module 16 · Lesson 01

Type Annotations

Describe the types your code expects with annotations: parameters, return values and variables, list[int] and dict[str, float], X | None, Callable and generics, and how type checkers use them while Python itself does not enforce them.

  • About 9 minutes
  • Builds on earlier lessons
  • 12-question quiz at the end

What you will learn

  • Annotate a function
  • Hints, not checks
  • Values that may be None
  • Watch annotated code run

Say what types you mean

Annotations describe what a function expects and returns. Python stores them; tools check them.

  • Parameters

    def greet(name: str) -> str: says a string goes in and a string comes out.

  • Collections

    list[int], dict[str, float] and tuple[int, str] describe what is inside.

  • Maybe missing

    str | None warns everyone that the answer might be None.

  • Hints, not rules

    Python does not check them while running. A type checker such as mypy does.

Annotations everywhere

Big code bases lean on annotations to stay readable.

  • EditorsYour editor uses them to suggest methods and spot mistakes as you type.
  • Web APIsSome frameworks read annotations to check and convert incoming data.
  • Dataclasses@dataclass builds __init__ from the annotated fields of a class.
  • Team workA typed signature tells a teammate how to call your function without reading it.

Reading an annotated signature

This first line of a function says what goes in and what comes out. Tap each part to see its job.

Part 1 of 5

Tap any part of the code below, or press Next.1 of 5 explored

colon:Separates a parameter's name from its type.

Describe your types

Pick an example, change it, then press Run. Say what you expect to see before you press.

Example 1 of 6Annotate a function

Annotations sit in the first line. The body is ordinary Python.

Your turn: Add a third parameter vip: bool = False and use it in the message.

Python
def welcome(name: str, visits: int = 1) -> str:
    return f"Welcome back, {name}! Visit number {visits}."

print(welcome("Ana"))
print(welcome("Ben", 5))
print(welcome("Cai", visits=2))
Output
Press Run to see what it prints.

Watch annotated code run

Press Step to run one line at a time. Watch the names box change.

Ready. Press Step to run the first line.

  1. def total(prices: list[float], tax: float = 0.2) -> float:
  2. subtotal = sum(prices)
  3. return round(subtotal * (1 + tax), 2)
  4. bill = total([4.0, 6.0])
  5. print(bill)
  6. print(total([10.0], tax=0))

Output so far

Nothing printed yet.

What Python does

Python reads the program from the top. Nothing has run yet.

Names

None yet.

Quick guesses

Guess first, then read why. A wrong guess is where the learning happens. Nothing here is scored.

Question 1 of 6

1.The annotation says int:

def half(n: int) -> int:
    return n / 2
print(half(5))

0 of 6 answered

Common annotation misconceptions

Each card is something learners often believe. Tap it to see what Python really does.

Misconception 1 of 4

Notes

Everything above, in words. Open it when you want the full explanation.

Read the notesOpen

Annotations are hints

An annotation is a note about the type a value is expected to have. You write it after a colon for parameters and variables, and after an arrow for a function's return value:

Try it 1: edit me, then Run
def format_price(cents: int, currency: str = "$") -> str:
    return f"{currency}{cents / 100:.2f}"

discount: float = 0.15
Output
Press Run to see what it prints.

Read the first line as "format_price takes an int called cents and an optional str called currency, and returns a str". The default value goes after the annotation.

The single most important fact about annotations: Python does not check them when the program runs. They are stored and can be read, but nothing stops you passing the wrong type:

Try it 2: edit me, then Run
def double(n: int) -> int:
    return n * 2

print(double("ab"))      # abab, no error
Output
Press Run to see what it prints.

Their job is to inform people and tools. Editors and type checkers, programs like mypy and pyright that read your code without running it, compare each call with the annotations and report mismatches such as double("ab") before the code ever runs. That is how annotations catch bugs: early, and across the whole project.

Basic types

Any class can be an annotation: int, float, str, bool, bytes, and your own classes, such as def pay(account: Account) -> None:. A function that returns nothing useful is annotated -> None. As a convenience, checkers accept an int wherever a float is expected.

Collections

For containers, put the type of the items in square brackets:

Try it 3: edit me, then Run
names: list[str] = ["ana", "ben"]
stock: dict[str, int] = {"mug": 4}
point: tuple[float, float] = (2.5, -1.0)      # exactly two floats
readings: tuple[float, ...] = (1.0, 2.5, 3.0)  # any length
tags: set[str] = {"new", "sale"}
Output
Press Run to see what it prints.

A dict takes two types, the keys' and the values'. A tuple lists the type of each position, or one type followed by ... for "any number of these". Collections can nest: dict[str, list[int]] maps names to lists of numbers.

Unions and missing values

When a value can be one of several types, join them with |:

Try it 4: edit me, then Run
def to_cents(amount: int | float | str) -> int:
    return round(float(amount) * 100)
Output
Press Run to see what it prints.

The most common union is "a value or nothing". str | None means "a string, or None":

Try it 5: edit me, then Run
def find_email(name: str, book: dict[str, str]) -> str | None:
    return book.get(name)
Output
Press Run to see what it prints.

This annotation is a warning to callers: the result might be None, so check before using it. Type checkers enforce exactly that: calling .lower() on the result without an if email is not None: check is reported as an error. In older code you will see the same idea written as Optional[str], imported from typing.

Functions as values: Callable

Higher-order functions take other functions. Callable from collections.abc describes them by their parameter types and return type:

Try it 6: edit me, then Run
from collections.abc import Callable

def apply(values: list[float], rule: Callable[[float], float]) -> list[float]:
    return [rule(v) for v in values]
Output
Press Run to see what it prints.

Callable[[float], float] means "something you can call with one float that returns a float". In the same module, Iterable[str] accepts any iterable of strings (a list, a set, a generator) and Iterator[int] describes what a generator function returns.

Generic functions

Some functions work for any type but keep it consistent, like "return the first item of a list, whatever the items are". A type parameter in square brackets after the name expresses that:

Try it 7: edit me, then Run
def first[T](items: list[T]) -> T:
    return items[0]
Output
Press Run to see what it prints.

For a checker, first(["a", "b"]) is a str and first([1, 2]) is an int. This bracket syntax arrived in Python 3.12; older code uses T = TypeVar("T") from typing for the same thing.

Naming complex types

Long types can be given a name, a type alias, so they are written once:

Try it 8: edit me, then Run
type Scores = dict[str, list[int]]

def best(scores: Scores) -> str: ...
Output
Press Run to see what it prints.

The type statement is new in 3.12; a plain assignment Scores = dict[str, list[int]] also works.

Annotations at runtime

Annotations are stored in a function's __annotations__ dictionary, and some tools read them. The best-known example is dataclasses, which uses the annotated class attributes to write __init__, __repr__ and __eq__:

Try it 9: edit me, then Run
from dataclasses import dataclass

@dataclass
class Product:
    name: str
    price: float = 0.0

print(Product("pen", 1.5))   # Product(name='pen', price=1.5)
Output
Press Run to see what it prints.

Even here the types are not enforced: Product(3, "x") is accepted. When data arrives from outside your program (user input, files, network requests) you still need real checks, with isinstance or int(...) conversions, at the point where it enters.

How much to annotate

Annotate the boundaries first: the parameters and return types of functions that other code calls. Local variables rarely need annotations, because checkers work out their types from the assigned values. An annotation that lies is worse than none, so keep them accurate when the code changes, and let a checker in your editor or test run tell you when they drift.

Syntax

The general shape of the statements in this lesson.

syntax.py
def f(x: int, name: str = "a") -> bool: ...   # parameters and return
count: int = 0                                 # variable
def log(msg: str) -> None: ...                 # returns nothing

list[str]   dict[str, int]   set[int]          # collections
tuple[int, str]   tuple[float, ...]            # fixed / any length
int | str          str | None                  # unions, optional

from collections.abc import Callable, Iterable, Iterator
Callable[[int, int], int]                      # takes two ints, returns int

def first[T](xs: list[T]) -> T: ...            # generic (3.12+)
type Scores = dict[str, list[int]]             # alias (3.12+)

f.__annotations__                              # stored, not enforced
Output
Press Run to see what it prints.

Worked examples

Read the problem, run the code, then read why it works.

Example 1 of 2

An annotated invoice, and what annotations do not do

Beginner

Write annotated functions that total an invoice from (item, cents, quantity) lines and format the result. Then show that a wrong type is not caught at runtime, and add a real check where outside data enters.

Python
def line_total(cents: int, quantity: int) -> int:
    return cents * quantity

def invoice_total(lines: list[tuple[str, int, int]]) -> int:
    return sum(line_total(cents, qty) for _, cents, qty in lines)

def format_cents(cents: int) -> str:
    return f"${cents // 100}.{cents % 100:02}"

lines = [("notebook", 349, 2), ("pen", 120, 5)]
print(format_cents(invoice_total(lines)))
print(line_total.__annotations__)

print(repr(line_total("12", 3)))

def parse_quantity(text: str) -> int:
    if not text.strip().isdigit():
        raise ValueError(f"not a quantity: {text!r}")
    return int(text)

print(line_total(349, parse_quantity(" 3 ")))
Output
Press Run to see what it prints.

Predict first

How it works(open after your guess)

The annotations document every function at a glance and are stored in __annotations__. Yet line_total("12", 3) runs and repeats the string, because Python does not enforce them. A type checker would flag that call; at runtime, parse_quantity does the real checking where text from outside becomes a number.

Common pitfalls

Mistakes people make with this topic, and what to write instead.

Pitfall 1 of 3

Expecting annotations to convert or check values

Spot the bug

Can you see what is wrong? Run it to watch it go wrong, then open the fix.

Buggy code: run it
def add(a: int, b: int) -> int:
    return a + b

print(add('4', '5'))
Output
Press Run to see what it prints.
Show what goes wrong and the fix

What happens

Prints 45 instead of 9, with no error

Write this instead

def add(a: int, b: int) -> int:
    return a + b

print(add(int('4'), int('5')))

Why it happens

Annotations are hints for tools; Python runs the function with the strings it was given.

In the real world

Where this shows up in software people use every day.

  1. Checking incoming settings against annotations

    Backend services

    A service loads its settings from a JSON-like dictionary. The team already annotates a settings class, so instead of writing a separate list of expected types they read the annotations at startup with typing.get_type_hints and refuse to start on a mismatch.

    Why Python fits

    get_type_hints returns the annotated fields and their types, so the check always matches the class. The loader turns the hints into a real runtime check at the one place where untrusted data enters; inside the program, the dataclass and its annotations can then be trusted, and a type checker covers the rest.

    Python
    from dataclasses import dataclass
    from typing import get_type_hints
    
    @dataclass
    class Settings:
        host: str
        port: int
        debug: bool = False
    
    def load(raw: dict[str, object]) -> Settings:
        hints = get_type_hints(Settings)
        problems = []
        for name, expected in hints.items():
            if name in raw and not isinstance(raw[name], expected):
                problems.append(f"{name} should be {expected.__name__}, got {type(raw[name]).__name__}")
        unknown = set(raw) - set(hints)
        if unknown:
            problems.append(f"unknown keys {sorted(unknown)}")
        if problems:
            raise TypeError("; ".join(problems))
        return Settings(**raw)
    
    print(load({"host": "api.local", "port": 8080}))
    try:
        load({"host": "api.local", "port": "8080", "colour": "red"})
    except TypeError as error:
        print("refused:", error)
    Output
    Press Run to see what it prints.

Key takeaways

Tick each one you could explain to a friend.

0 of 5

Common questions

Guess the answer first, then open it.

Do annotations make my program slower or faster?

Neither, in practice. They are stored, not executed as checks, so they cost almost nothing at runtime and do not speed anything up.

How do I run a type checker?

Install one, for example with pip install mypy, and run mypy myfile.py. Many editors run pyright or a similar checker automatically and underline problems as you type.

What is the Any type?

Any, from typing, switches checking off for a value: anything is allowed in and out. It is useful when moving old code to annotations, but each Any is a place where the checker cannot help you.

Should I annotate every variable?

No. Annotate function signatures and class attributes; checkers infer most local variable types. Add a variable annotation when the type is not obvious, such as an empty list that will hold strings: names: list[str] = [].

Your notes

Sign in to keep private notes alongside this lesson.

Sign in to take notes

Where to go next

The quiz and the Lab live on their own pages, so this lesson stays about learning.

Finished this lesson?

Create an ID or sign in to save your progress across devices.

Create ID to save
Lessons done in this module0/3 complete
Quiz

Check what you learned

12 questions, with an explanation after every answer. A verified attempt counts towards opening the module Lab.

Lab

Keep going in the Lab

7 tasks on this lesson, from writing code to tracing it by hand. Practice only, no XP.

Review

Spaced review

Questions you miss in a quiz come back on a spaced schedule, so what you learned here sticks.

This lesson at a glance

The 11 lines of code this lesson uses, each with a short note. Keep it open while you do the quiz and the Lab.

What else you can search for and explore

Curious to go further? Each card opens a web search in a new tab.

References

Look things up here whenever you need the exact details.