Sub topic 4
Required and optional keys: total, Required, NotRequired
This chapter assumes you can define a TypedDict with the class syntax, know basic type hints such as str and Optional, and run a static checker such as mypy or pyright. The checker reads these rules. Python itself never enforces them.
Every key is required by default
A key you declare in a TypedDict must be present. A checker reports a dictionary literal that leaves one out.
from typing import TypedDict
class User(TypedDict):
id: int
name: str
ok: User = {"id": 1, "name": "Alice"}
missing: User = {"id": 2} # flagged by the checker: "name" is missingReal data often has keys that may be absent, such as an optional email address. There are two ways to say so.
Making all keys optional with total=False
Pass total=False in the class header. Every key declared in that class becomes optional.
from typing import TypedDict
class Options(TypedDict, total=False):
timeout: float
retries: int
opts: Options = {}
print(opts.get("timeout", 10.0))An empty dictionary is a valid Options. The default is total=True.
Marking single keys with NotRequired and Required
total applies to the whole class. To change one key, wrap its type.
from typing import NotRequired, Required, TypedDict
class Profile(TypedDict):
id: int
email: NotRequired[str]
class Settings(TypedDict, total=False):
id: Required[int]
theme: str
def contact(profile: Profile) -> str:
if "email" in profile:
return profile["email"]
return "no email on file"
print(contact({"id": 1}))
print(contact({"id": 2, "email": "[email protected]"}))Profile is mostly required with one optional key. Settings is mostly optional with one required key. Choose whichever form needs fewer wrappers.
| Declaration | `id` | `email` |
|---|---|---|
| `class P(TypedDict)` with `email: NotRequired[str]` | required | optional |
| `class P(TypedDict, total=False)` with `id: Required[int]` | required | optional |
| `class P(TypedDict, total=False)` | optional | optional |
A wrapper on a single key overrides total for that key.
Reading optional keys safely
Indexing an optional key with profile["email"] is flagged, because it could raise KeyError. The checker accepts these patterns:
- Test membership first with
"email" in profile, then index inside the branch. - Use
profile.get("email"), which returnsNonewhen the key is absent, orprofile.get("email", "default").
Exercise
You want a Job dictionary where name is required, and priority and tags are optional. Write the class using total=False and Required, then say how you would read priority with a default of 0.
Show answer
class Job(TypedDict, total=False): name: Required[str]; priority: int; tags: list[str]. Read it with job.get("priority", 0), or check "priority" in job before using job["priority"].