Skip to the workspace
Pebellslearn by building
Fundamentals  ›  Lesson

Type Annotations

Type Annotations 20 minType annotations describe the kinds of values code expects and returns; Python does not generally enforce them automatically at runtime.

Type annotations describe the kinds of values code expects and returns; Python does not generally enforce them automatically at runtime.

Write readable function contracts and learn where runtime checks must establish the assumptions that annotations express.

A function signature can tell a reader what values are accepted and what may come back. Type annotations make that promise available to a checker. We will follow a possibly missing price through its caller to see what a checker can establish and what still needs runtime validation.

The signature def double(n: int) -> int is called with "ab"; when Python runs it the labels are skipped and it quietly returns "abab", while a checker reading the same code flags that "ab" is a str where an int was expected

Format a receipt line

A canteen prints one line per item. With labels, the signature tells you how to call it without reading the body:

python

Read it as: takes a str called name and a float called price, returns a str. An int like 10 is fine where a float is expected. Now the price comes from a text box, and everything typed into a form arrives as a string:

What happens when you run this?
def receipt_line(name: str, price: float) -> str:
    return f"{name}: ₹{price:.2f}"

typed_in = "10"
print(receipt_line("Chai", typed_in))

People expect the label to convert or reject the value. It does neither. The fix is to convert once, where the text enters your program, so everything after that point really gets a float:

python

Preparing this topic’s interactive investigation…

Look up a menu price

The menu is a dict from dish name to price, and a dish might be missing. The labels say both things:

python

dict[str, float] means string keys and float values. float | None is the return label's warning: this can come back empty. Code that ignores the warning breaks on the first missing dish:

broken — fix itTypeError

One dish is not on the menu and the whole order crashes. Skip dishes that have no price.

A checker would have pointed at total += … before you ran anything, because the label promised None was possible. Two names you will see in older code mean the same thing: Optional[float] is float | None, and Union[int, str] is int | str (both from typing).

Trap: | None (or Optional) means the value may be None. It does not mean the argument can be left out. Only a default does that: def find_price(menu, dish, fallback: float | None = None).

A check narrows what can happen next

With return type float | None, a caller starts with two possibilities. After if price is None: return ..., the remaining branch only handles numbers. A static checker uses this narrowing to verify later operations:

python

if not price would combine missing with zero; the explicit check preserves free items. Annotating an argument as optional and making it optional to supply are independent: the union allows a value; = None supplies a default. An annotation never performs either a numeric conversion or a value-range check.

Read the syntax from outside inward: list[dict[str, float]] means a list of dictionaries, each with string keys and float values. It cannot describe “this dict must have exactly price and quantity”; that needs named fields, as in the next example.

Describe a train ticket

For data with a fixed set of fields you have two tools. A TypedDict describes a plain dict key by key, which suits data that arrives as JSON. A @dataclass turns labelled fields into a small class and writes the constructor, the printout and == for you:

python

Now give each ticket a list of seats that starts empty:

broken — fix itValueError

The class will not even build. Give every ticket its own empty list.

One-liners you'll meet

python

You will also see List[int] and Dict[str, int] (capitalised, imported from typing) in code written before Python 3.9. They mean the same as list[int] and dict[str, int].

A type describes a boundary; parsing enforces it

A TypedDict helps a checker reason about named keys, but the runtime object is an ordinary dict. It does not validate incoming JSON. A dataclass generates methods such as initialization and representation; its annotations also do not reject wrong field types by themselves. Validation still belongs where untrusted text or records enter your program.

Any permits operations a checker would otherwise question. It is useful at an uncertain boundary, but information remains unchecked until you validate or narrow it. Also, Python's version affects how annotations are stored/evaluated; their non-enforcement of the declared value types is the point this lesson relies on.

As a transfer task, annotate a lookup that can return a record or None, then write a caller that handles both cases before reading the record. State which malformed input a checker might flag in source and which input can only be discovered at runtime. The exercises' execution tests verify outputs; run a type checker separately to verify the annotations themselves.

Quick practice

What does this print?
def add(a: int, b: int) -> int:
    return a + b

print(add("5", "5"))
What happens when you run this?
count: int
print(count)
What happens when you run this?
def greet(name: str | None) -> str:
    return f"Hi {name or 'guest'}"

print(greet())
broken — fix itTypeError

The function breaks its own -> int promise. Make it keep it.


🎯 Your turn

Write receipt_line(name, price) with type annotations. It returns one line of the receipt as "name: $price", with the price to two decimals:

  • receipt_line("Soup", 10) → "Soup: $10.00"
  • receipt_line("Steak", 20.5) → "Steak: $20.50"

Hint: label the signature def receipt_line(name: str, price: float) -> str:, then return f"{name}: ${price:.2f}". The tests check the returned string, so the labels are for readers and checkers.

Press ▶ Run, try the Live App chips, then ✓ Check. After that, the practice set below goes from counting words to grouping orders by table, all typed.

Your task
Build receipt_line(name, price) — WITH type annotations — that returns one receipt line as 'name: $price' (price to 2 decimals). Annotate it: name is a str, price is a float, it returns a str. Example: receipt_line("Soup", 10) → "Soup: $10.00".

Practice — level up

0/5 solved

Solve each in its own editor — Run to try, Check to grade. Stuck? Reveal a Hint, or the full Solution + walkthrough.

Warm-upCount words (typed)

Write count_words(text: str) -> int returning how many whitespace-separated words text has.

annotations
DrillActive users

A user is {"name": str, "active": bool}. Write active_names(users) returning the names of active users only. Type it with a TypedDict.

TypedDictcomprehension
BuildCart total (typed)

A cart item is {"name": str, "price": float, "qty": int}. Write total_price(cart) returning the grand total (price × qty summed), rounded to 2 decimals. Type it.

TypedDictgeneratorround
BossOrder summary (typed)

An order is {"table": int, "total": float}. Write order_summary(orders) returning {"tables": <count>, "revenue": <sum of totals>, "biggest": <the order with the max total>}. Empty → counts 0 and "biggest": None.

TypedDictmax-keyguard
CapstoneGroup orders by table (typed)

An order is {"table": str, "dish": str}. Write group_orders(orders) returning a dict mapping each table id to its list of dishes, order preserved. Type it.

TypedDictsetdefault
Project context and further resources
You're building a piece ofBill Splitter & Tip Calculator
This piece — receipt_line(): Formats one line of the printed receipt.
Scenario Every line on the printed receipt reads 'Dish: $price'. This formats one line — and we annotate it so anyone reading the code knows exactly what goes in and what comes out.
receipt_line.py
Call the function you wrote — just like your app's frontend would. Edit the inputs and hit Call.
receipt_line(name, price) → strOne formatted line of the printed receipt.
try:
returned
Press Run to execute your code.
Press Check to run the tests for this lesson.
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.