Sub topic 1
Python TypedDict and Literal Types: Precise Types for Dictionaries and Fixed Values
Prerequisites
Assume you know Python dictionaries, functions, classes, and basic type hints. A static type checker such as mypy or pyright checks annotations separately from running your program.
Why `dict[str, Any]` is not enough
dict[str, Any] says that keys are strings and values may have any type. It does not describe which keys should exist or what each key means.
This hides mistakes. A misspelled key and an integer where a string is expected can pass static checking. Use TypedDict when a dictionary has a known set of named fields.
Describing a dictionary's shape with `TypedDict`
A TypedDict describes the expected keys and the type of each value. It remains dictionary-shaped, so functions can accept and return ordinary dictionaries.
from typing import TypedDict
class Movie(TypedDict):
title: str
year: int
def describe(movie: Movie) -> str:
return f"{movie['title']} ({movie['year']})"
movie: Movie = {"title": "Blade Runner", "year": 1982}
print(describe(movie))A checker can report a missing key, an unknown key, or an incompatible value type. These checks do not validate data supplied at runtime.
Restricting values with `Literal`
Literal restricts a type to specific constant values. This is useful for modes, statuses, and other small fixed choices.
from typing import Literal
def open_log(path: str, mode: Literal["r", "w", "a"]) -> None:
print(f"opening {path} with mode {mode}")
open_log("app.log", "r") # accepted by a type checker
open_log("app.log", "x") # reported by a type checkerThe second call still runs in normal Python. Literal provides static information, not runtime validation.
Required and optional keys: `total`, `Required`, `NotRequired`
By default, every TypedDict key is required. total=False makes keys optional. Use Required and NotRequired when a single class needs both kinds of keys.
from typing import NotRequired, Required, TypedDict
class Movie(TypedDict, total=False):
title: Required[str]
year: Required[int]
director: NotRequired[str]
movie: Movie = {"title": "Arrival", "year": 2016}
if "director" in movie:
print(movie["director"])Check an optional key before indexing it. The key might be absent even when the dictionary has the correct type.
Exercise
Which annotation describes a dictionary with a required id key and an optional email key?
Show answer
class User(TypedDict): id: int; email: NotRequired[str]