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]andtuple[int, str]describe what is inside.Maybe missing
str | Nonewarns 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
@dataclassbuilds__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
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.
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))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.
- def total(prices: list[float], tax: float = 0.2) -> float:
- subtotal = sum(prices)
- return round(subtotal * (1 + tax), 2)
- bill = total([4.0, 6.0])
- print(bill)
- 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 notesNotesOpenClose
Syntax
The general shape of the statements in this lesson.
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
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
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.
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 ")))Press Run to see what it prints.Predict first
How it works(open after your guess)
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.
def add(a: int, b: int) -> int:
return a + b
print(add('4', '5'))Press Run to see what it prints.Show what goes wrong and the fixWhat goes wrong and the fix
In the real world
Where this shows up in software people use every day.
- Backend services
Checking incoming settings against annotations
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_hintsreturns 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.Pythonfrom 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)OutputPress 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?
How do I run a type checker?
What is the Any type?
Should I annotate every variable?
Your notes
Sign in to keep private notes alongside this lesson.
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.
Check what you learned
12 questions, with an explanation after every answer. A verified attempt counts towards opening the module Lab.
Keep going in the Lab
7 tasks on this lesson, from writing code to tracing it by hand. Practice only, no XP.
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.