Command Palette

Search for a command to run...

Hectal
Back to the lesson: Topic 10.2 — Typing Collections, Optional and Unions
Python · Example 1 of 3

Collection and callable hints, read back

get_type_hints shows the labels exactly as a library or checker sees them.

Hints for containers say what is inside: list[int], dict[str, int], tuple[int, str]. X | None means "an X, or nothing", and Sequence, Mapping, Iterable and Callable describe what a function needs without demanding one exact class.

Change the code and press Run (Ctrl+Enter). Predict what will happen first, then break it on purpose and read what changes. Your edits are saved and match the lesson page.

Ready for more? This phase has 5 hands-on exercises with automatic checks.

Practice questions

Write the code in the editor, run it, then open the model answer to compare.

01

Write first_or_none(items: list[int]) -> int | None that returns the first item or None for an empty list. Print the result for [7, 8] and [].

02

Write describe(value: int | str) -> str returning "number 5" or "text hi" using isinstance.

03

Write call_twice(fn: Callable[[int], int], x: int) -> int that returns fn(fn(x)) and call it with a lambda that adds 3 to 10.

Explain it without notes

01

How do you write the type of a list of integers, and which Python version made the plain list[int] form possible?

02

What does str | None mean, and how is it different from a parameter with a default value?

03

Why hint a function parameter as Iterable[int] instead of list[int]?

04

What is narrowing?

05

Why does a checker reject passing a list[int] to a function that takes list[float], yet accept it for Sequence[float]?

Collection and callable hints, read back
Sign in to run this example in your browser.

Expected output

average {'scores': list[int], 'return': <class 'float'>}
find_user {'users': dict[str, int], 'name': <class 'str'>, 'return': int | None}
old_style {'name': typing.Optional[str], 'return': <class 'str'>}
apply {'values': collections.abc.Iterable[int], 'fn': collections.abc.Callable[[int], int], 'return': list[int]}
total {'prices': collections.abc.Mapping[str, float], 'skip': collections.abc.Sequence[str], 'return': <class 'float'>}
1 None
[0, 10, 20]
20.0
(3, 4) (1, 2, 3, 4)