Command Palette

Search for a command to run...

Hectal
Back to the lesson: Topic 10.5 — TypedDict, NamedTuple, Literal and Final
Python · Example 1 of 3 Python 3.11+

TypedDict, Literal, NamedTuple and Final at run time

At run time a TypedDict is a dict, nothing is enforced, and the class remembers which keys are required.

These tools describe specific shapes: TypedDict labels the keys of a dictionary, NamedTuple gives tuple fields names, Literal allows only listed values, Final marks a constant, and Self, Annotated and @override cover methods that return their own class, extra metadata and overriding.

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

Define a TypedDict named ToolCall with name: str and arguments: dict[str, str], create one, and print its __required_keys__ sorted.

02

Define a NamedTuple Rgb with r, g, b ints and print Rgb(255, 0, 0) and its g value.

03

Define a type Mode = Literal["fast", "slow"] and print its allowed values using get_args.

Explain it without notes

01

What is a TypedDict at run time, and what does it give you at all?

02

When would you use Literal instead of str?

03

Why is -> Self better than naming the class when a method returns self?

04

How does a NamedTuple differ from a plain tuple and from a dataclass?

05

Can you validate that a dictionary matches a TypedDict at run time with isinstance? What would you do instead?

TypedDict, Literal, NamedTuple and Final at run time Python 3.11+
Sign in to run this example in your browser.

Expected output

{'role': 'user', 'content': 'Hello'} dict
is a plain dict: True
bad role is accepted at run time: {'role': 'robot', 'content': 'x'}
required: ['content', 'role']
optional: ['name']
Options required: ['model']
roles: ('user', 'assistant', 'system')
Point(x=3, y=0) 3 0 {'x': 3, 'y': 0}
unpacked: 3 0
MAX_TOKENS = 4096
MAX_TOKENS now 1