TypedDict
A TypedDict describes which keys a dict has and what type each value is, while it stays a plain dict.
Used in 13 lessons of the course, from 01.04.
A TypedDict is a class that declares the shape of a dict: its keys and the type of each value.
class EventDict(TypedDict):
name: str
count: int
Read it like this: an EventDict is a dict with a "name" key (a string) and a "count" key (an int).
The key point: at runtime it is still a plain dict. Python checks nothing. The annotations are for editors and type checkers, which warn you if you use a key that doesn't exist or a wrong type.
You use it because a lot of data travels as dicts (JSON, for example), and this makes clear what each one holds. In the course, class EventDict(TypedDict): appears from lesson 01.04 to describe the state passed between steps.
You create one by calling the class with keyword arguments or with a dict literal.
Reach for it when: you pass dicts with fixed keys around your code and want to document and type-check their shape.
Examples
Common mistake
from typing import TypedDict
class Event(TypedDict):
name: str
e = Event(name="a")
print(e.name)Why: Even though it looks like a class, the result is a dict. It has keys, not attributes.
How to write it: Use square brackets: e["name"].
Common mistake
from typing import TypedDict
class Event(TypedDict):
count: int
e: Event = {"count": "three"}
print(e)Why: Python doesn't check types at runtime. Only a type checker would flag the error.
How to write it: Pass an int (3) and run a type checker on your code; if you need runtime validation, use pydantic.
