Sub topic 4
Required and optional keys: total, Required, NotRequired
This chapter assumes you can define a basic TypedDict with the class syntax, that you know Optional and Literal at a basic level, and that you run a static checker such as mypy or pyright separately from your code. The examples use NotRequired and Required, which live in typing from Python 3.11. On older versions, import them from typing_extensions.
What "required" means in a TypedDict
By default, every key in a TypedDict is required. A dictionary that omits one of them does not match the type, and the checker reports it.
from typing import TypedDict
class Movie(TypedDict):
title: str
year: int
ok: Movie = {"title": "Alien", "year": 1979}
missing: Movie = {"title": "Alien"} # flagged by a type checker: "year" is missing
print(ok, missing)The last line runs without error, because the runtime does not check the shape. Only the checker complains.
Real data often has keys that may be absent: an optional email address, a request option, a field added in a later API version. There are three tools for this:
- The
totalclass argument, which sets the default for every key in one class body. NotRequired[...], which marks one key as optional.Required[...], which marks one key as required.
The total argument
total=True is the default. Passing total=False makes every key declared in that class body optional.
from typing import TypedDict
class Options(TypedDict, total=False):
timeout: float
retries: int
empty: Options = {}
partial: Options = {"timeout": 2.5}
full: Options = {"timeout": 2.5, "retries": 3}
print(empty, partial, full)All three assignments are valid. An optional key can be absent, but if it is present its value must still match the declared type. {"timeout": "fast"} is an error.
NotRequired and Required for single keys
total applies to a whole class. NotRequired and Required let you override it for one key, so a class can mix both kinds without splitting it up.
from typing import NotRequired, TypedDict
class User(TypedDict):
id: int
name: str
email: NotRequired[str]
alice: User = {"id": 1, "name": "Alice"}
bob: User = {"id": 2, "name": "Bob", "email": "[email protected]"}
print(alice, bob)The reverse case uses Required inside a total=False class:
from typing import Required, TypedDict
class Search(TypedDict, total=False):
query: Required[str]
limit: int
offset: int
s1: Search = {"query": "typeddict"}
s2: Search = {"query": "literal", "limit": 10}
print(s1, s2)Here query must be present, while limit and offset may be absent. Both spellings of a class describe the same type, so pick the one with fewer annotations. If most keys are optional, use total=False with Required on the exceptions. If most keys are required, keep the default and use NotRequired.
| Declaration | Key must be present? |
|---|---|
| `key: int` in a normal class | Yes |
| `key: int` in a `total=False` class | No |
| `key: NotRequired[int]` in any class | No |
| `key: Required[int]` in any class | Yes |
The explicit wrapper always wins over total. Writing Required[...] in a default class, or NotRequired[...] in a total=False class, is legal but redundant.
Optional key versus Optional value
NotRequired[str] and Optional[str] look similar but answer different questions.
| Annotation | Key may be missing? | Value may be `None`? | Column |
|---|---|---|---|
| `email: str` | No | No | |
| `email: NotRequired[str]` | Yes | No | |
| `email: str \ | None` | No | Yes |
| `email: NotRequired[str \ | None]` | Yes | Yes |
Choose based on what your data really does. A JSON payload that sends "email": null needs str | None. A payload that leaves the key out needs NotRequired. APIs that do either need both. Using Optional[str] when the key can be absent is a common mistake. The checker then insists the key is always present, and your code fails with KeyError on real input.
Reading optional keys safely
A checker treats subscripting an optional key as unsafe, because the key might not exist. Pyright reports this. Mypy is more lenient by default, so don't rely on it to catch the mistake. There are three safe patterns.
from typing import NotRequired, TypedDict
class User(TypedDict):
id: int
name: str
email: NotRequired[str]
def contact_line(user: User) -> str:
# 1. Membership test: the checker narrows the key as present.
if "email" in user:
return f"{user['name']} <{user['email']}>"
return user["name"]
def email_or_default(user: User) -> str:
# 2. .get with a default: no KeyError, result is always a str.
return user.get("email", "no email on file")
def email_or_none(user: User) -> str | None:
# 3. .get without a default: result is str | None.
return user.get("email")
alice: User = {"id": 1, "name": "Alice"}
print(contact_line(alice))
print(email_or_default(alice))
print(email_or_none(alice))This prints:
Alice
no email on file
NoneUse in when you need the value and want the checker to prove the key exists. Use .get when a fallback is fine. Note that .get cannot tell a missing key from a key whose value is None when the value type includes None.
Deleting a key has a similar rule. del user["email"] is allowed, because the key is optional. del user["id"] is flagged, because removing a required key would make the dictionary no longer match the type.
Mixing keys in inheritance
When a TypedDict inherits from another, total applies only to the keys declared in the new class body. Inherited keys keep whatever status they had.
from typing import TypedDict
class Base(TypedDict):
id: int
class Child(Base, total=False):
note: str
c1: Child = {"id": 1}
c2: Child = {"id": 1, "note": "hi"}
print(c1, c2)id stays required because Base is total=True. Only note is optional. This is the older way to build a "some required, some optional" type before Required and NotRequired existed. It still works. It needs two classes where the wrapper approach needs one.
What happens at runtime
Nothing is enforced. The key sets are recorded as metadata that you can inspect, and the checker uses the same information.
from typing import NotRequired, Required, TypedDict
class Config(TypedDict):
host: str
port: NotRequired[int]
class Tuned(TypedDict, total=False):
name: Required[str]
cache_size: int
print(sorted(Config.__required_keys__), sorted(Config.__optional_keys__))
print(sorted(Tuned.__required_keys__), sorted(Tuned.__optional_keys__))
broken = Config(port=8080) # no "host", and no error at runtime
print(broken)The output is:
['host'] ['port']
['name'] ['cache_size']
{'port': 8080}The Config(port=8080) call builds an ordinary dictionary that is missing a required key. A checker flags it. Python does not. If the data comes from a file, a network call or a user, validate it yourself or with a validation library, because the annotations will not do it for you.
Where the wrappers are allowed
Required and NotRequired are only meaningful as the outermost part of a TypedDict field annotation. These do not work:
- Using them in a function parameter or a variable annotation outside a
TypedDict. - Nesting them inside another type, such as
list[NotRequired[int]]. - Stacking both on one key, such as
Required[NotRequired[int]].
When a key's value type is a long union, put the wrapper on the outside: NotRequired[int | str | None].
Common errors
- Using
Optionalto mean "may be absent".Optional[str]allowsNone, but the key must still exist. UseNotRequired[str]. - Reading an optional key with
[]and no check. It raisesKeyErrorwhen the key is missing. Useinor.get. - Expecting
total=Falseon a child class to loosen inherited keys. It affects only the keys declared in that class body. - Assuming the runtime checks required keys. It does not. Only the checker, or your own validation, does.
- Importing
NotRequiredon Python 3.10 or earlier fromtyping. That raisesImportError. Import it fromtyping_extensions.
Exercise
A class is declared as class Event(TypedDict, total=False) with the fields name: Required[str], payload: dict[str, int] and retry: NotRequired[bool]. Which keys are required and which are optional? Which attribute on the class lets you confirm that at runtime?
Show answer
Only name is required. payload is optional because total=False applies to it, and retry is optional because of NotRequired (the wrapper is redundant here). You can confirm it with Event.__required_keys__, which is frozenset({'name'}), and Event.__optional_keys__, which is frozenset({'payload', 'retry'}).
Exercise
A JSON API sometimes omits the field nickname and sometimes sends "nickname": null. Write the field annotation for a TypedDict that accepts both, and give one safe way to read it into a str, using "anonymous" when no usable nickname is present.
Show answer
Use nickname: NotRequired[str | None]. One safe read is nick = user.get("nickname") or "anonymous". .get covers the missing key, and or covers None (and an empty string). If you must keep an empty string, test explicitly: value = user.get("nickname") then nick = value if value is not None else "anonymous".
Exercise
Given class A(TypedDict): x: int and class B(A, total=False): y: int, is {} a valid B? Is {"x": 1} valid?
Show answer
{} is not valid, because x is inherited from A as a required key, and total=False in B affects only y. {"x": 1} is valid, since y is optional.