Sub topic 10
The functional syntax for keys that are not identifiers
This chapter assumes you can write a class-syntax TypedDict and use NotRequired, as covered in the earlier chapters. You should also know that a type checker such as mypy or pyright reads these declarations, and Python itself does not enforce them.
The problem with class syntax
A class-syntax TypedDict declares each key as a class attribute. Attribute names must be valid Python identifiers, so the class syntax cannot describe these keys:
- Keys with hyphens or spaces, such as
"Content-Type"or"first name". - Keys that start with a digit, such as
"2fa". - Keys that are reserved words, such as
"class"or"from".
JSON APIs and HTTP headers often use keys like these. The functional syntax handles them because each key is an ordinary string.
Declaring a TypedDict by calling it
Call TypedDict with a name and a dictionary that maps each key to its type:
from typing import NotRequired, TypedDict
Headers = TypedDict(
"Headers",
{
"Content-Type": str,
"X-Request-Id": str,
"Accept": NotRequired[str],
},
)
headers: Headers = {
"Content-Type": "application/json",
"X-Request-Id": "abc123",
}
print(headers["Content-Type"])A type checker treats Headers exactly like a class-syntax TypedDict. The first argument is the class name, and it should match the variable you assign to. Checkers report a mismatch.
Required and optional keys work the same way as before. You can wrap a single value in NotRequired[...] or Required[...]. You can also pass total=False as a third argument:
from typing import TypedDict
Options = TypedDict(
"Options",
{"max-retries": int, "time out": float},
total=False,
)
opts: Options = {"max-retries": 3}
print(opts)Here both keys are optional, and the second key contains a space.
Reserved words as keys
The same technique covers keys such as class and for, which appear in HTML-like data:
from typing import TypedDict
Element = TypedDict("Element", {"class": str, "for": str, "id": str})
label: Element = {"class": "field", "for": "email", "id": "email-label"}
print(label["class"])Mixing both syntaxes
Functional syntax cannot declare methods or docstrings in the usual place, and it is harder to read for plain identifiers. A common compromise is to put the awkward keys in a small functional base and add the rest through inheritance:
from typing import TypedDict
_RequestHeaders = TypedDict(
"_RequestHeaders",
{"Content-Type": str, "X-Request-Id": str},
)
class Request(_RequestHeaders):
url: str
body: str
req: Request = {
"Content-Type": "text/plain",
"X-Request-Id": "r-1",
"url": "https://example.com",
"body": "hello",
}
print(sorted(req))Request requires all four keys. Inheritance works the same way for a functional base as for a class-syntax one.
Common errors
- The name string and the variable differ, as in
A = TypedDict("B", {...}). Checkers flag this. - The keys are not string literals. The dictionary must be written inline with literal string keys, because a checker cannot read keys that are built at runtime.
- The old keyword form,
TypedDict("P", x=int, y=int), was deprecated in Python 3.11 and removed in 3.13. Pass a dictionary instead.
Exercise
You receive JSON such as {"user-id": 7, "from": "web"}, where "from" is optional. Write a TypedDict named Event for it. Why can't you use class syntax?
Show answer
Event = TypedDict("Event", {"user-id": int, "from": NotRequired[str]}). Class syntax fails because "user-id" contains a hyphen and "from" is a reserved word, so neither can be written as a class attribute name.