Sub topic 10
The functional syntax for keys that are not identifiers
This chapter assumes you can write a class-syntax TypedDict, and that you know total, Required and NotRequired from the earlier chapters. You should also know that a type checker such as mypy or pyright reads annotations separately from running the code. The examples use NotRequired, so they need Python 3.11 or newer, or typing_extensions on older versions.
The problem: keys that are not valid names
The class syntax turns each key into a class attribute annotation:
from typing import TypedDict
class Movie(TypedDict):
title: str
year: intPython requires an attribute name to be a valid identifier. It must not contain hyphens, dots, spaces or @, it must not start with a digit, and it must not be a reserved keyword. Real data often breaks those rules:
- HTTP headers such as
Content-TypeandX-Request-ID. - JSON-LD fields such as
@typeand@context. - Flattened or namespaced keys such as
user.id. - Keys that are Python keywords, such as
class,fromandimport. - Keys that start with a digit, such as
2fa.
None of these can be written as name: type inside a class body. A dictionary can hold any string as a key, so the typing tool needs a way to describe those keys too. That way is the functional syntax.
The functional syntax
You call TypedDict like a function. The first argument is the class name as a string. The second is a dictionary that maps each key, written as a string, to its type.
from typing import TypedDict
Headers = TypedDict(
"Headers",
{
"Content-Type": str,
"Content-Length": int,
},
)
response_headers: Headers = {
"Content-Type": "application/json",
"Content-Length": 42,
}
print(response_headers["Content-Type"])
print(response_headers["Content-Length"] + 1)The result is the same kind of type that the class syntax produces. A checker accepts response_headers["Content-Type"] as a str and rejects response_headers["Content-Lenght"] as an unknown key. At runtime Headers is still a class whose instances are ordinary dictionaries.
Keys that are Python keywords
The same approach works for keywords and keys that start with digits:
from typing import TypedDict
Token = TypedDict(
"Token",
{
"class": str,
"from": str,
"2fa": bool,
},
)
token: Token = {"class": "admin", "from": "login-service", "2fa": True}
print(token["class"], token["2fa"])You cannot construct this with Token(class="admin"), because class is a syntax error as a keyword argument. Use a dictionary literal or Token(**some_dict), as shown later.
Optional keys in the functional form
Everything from the optional-keys chapter works here as well. You can pass total=False as a keyword argument, or you can wrap individual types in Required[...] and NotRequired[...].
from typing import NotRequired, TypedDict
Event = TypedDict(
"Event",
{
"user.id": int,
"action": str,
"from": NotRequired[str],
},
)
login: Event = {"user.id": 7, "action": "login"}
transfer: Event = {"user.id": 7, "action": "transfer", "from": "acct-1"}
if "from" in transfer:
print("source:", transfer["from"])Here user.id and action are required, and from is optional. As with the class syntax, the in check lets the type checker allow the read of transfer["from"].
For a mostly optional shape, use total=False and mark the few required keys with Required:
from typing import Required, TypedDict
Query = TypedDict(
"Query",
{
"q": Required[str],
"page-size": int,
"sort-by": str,
},
total=False,
)
print(Query.__required_keys__)
print(sorted(Query.__optional_keys__))Running this prints frozenset({'q'}) and ['page-size', 'sort-by'].
Combining both syntaxes with inheritance
You do not have to choose one syntax for a whole type. Put the awkward keys in a functional TypedDict and subclass it with the class syntax to add the keys that are valid identifiers. The subclass inherits every key, with the same required or optional status.
from typing import NotRequired, TypedDict, get_type_hints
_BaseHeaders = TypedDict(
"_BaseHeaders",
{
"Content-Type": str,
"X-Request-ID": NotRequired[str],
},
)
class Request(_BaseHeaders):
url: str
method: str
req: Request = {
"Content-Type": "text/plain",
"url": "https://example.com",
"method": "GET",
}
print(sorted(get_type_hints(Request)))
print(sorted(Request.__required_keys__))The first line prints all four keys: ['Content-Type', 'X-Request-ID', 'method', 'url']. The second prints the three required ones. Splitting the type this way keeps the readable part readable and confines the string-keyed part to one small definition.
A common arrangement is a private base for the wire-format keys, as above, and a public subclass for everything else.
Combining with Literal for tagged data
Keys such as @type are common in tagged data, and the functional syntax lets you use them as the tag in a tagged union. The checker narrows by the tag key exactly as it does for kind.
from typing import Literal, TypedDict
PersonNode = TypedDict("PersonNode", {"@type": Literal["Person"], "name": str})
OrgNode = TypedDict("OrgNode", {"@type": Literal["Organization"], "legalName": str})
Node = PersonNode | OrgNode
def label(node: Node) -> str:
if node["@type"] == "Person":
return node["name"]
return node["legalName"]
print(label({"@type": "Person", "name": "Ada"}))
print(label({"@type": "Organization", "legalName": "Analytical Engines Ltd"}))After the if check, a checker treats node as PersonNode inside the branch and as OrgNode after it. You can add assert_never for an exhaustiveness check, as in the tagged-union chapter.
Rules and gotchas
The class name must match the variable
The string you pass must equal the name you assign to. This is checked statically, and mypy reports a mismatch such as First argument "Foo" to TypedDict() does not match variable name "Bar". Pyright reports a similar error.
from typing import TypedDict
# Wrong: the string says "Foo" but the variable is Bar. A checker reports this.
Bar = TypedDict("Foo", {"a-b": int})At runtime this still runs. The class simply gets the name Foo, which produces confusing error messages later.
The fields must be a dictionary literal
Checkers analyze the code without running it. They can read a dictionary written directly in the call, with string literal keys. They cannot follow a dictionary built in a variable or computed in a loop.
from typing import TypedDict
fields = {"a-b": int}
Broken = TypedDict("Broken", fields) # a checker cannot read the keys; it reports an errorThis is the same reason a Literal argument cannot be a variable. Keep the definition fully written out.
The keyword form is gone
Older code sometimes wrote TypedDict("Point", x=int, y=int). That keyword form was deprecated in Python 3.11 and removed in 3.13. It could never express non-identifier keys, so use the dictionary form in all new code.
Construction and `Unpack` are limited by Python syntax
The call form Headers(Content-Type="x") is invalid Python, so you build these values with a dictionary literal, or by passing a dictionary to the constructor:
from typing import TypedDict
Headers = TypedDict("Headers", {"Content-Type": str, "Content-Length": int})
raw = {"Content-Type": "text/html", "Content-Length": 10}
h = Headers(**raw)
print(h)The constructor does not validate its input. It works like dict(**raw), as the runtime chapter explained.
For the same reason, a non-identifier key cannot be a named keyword parameter. If you type **kwargs with Unpack, a key such as Content-Type can only reach the function through **dict unpacking and not through a normal call like f(Content-Type=...). Prefer a plain Headers parameter for such shapes.
Choosing a syntax
| Situation | Syntax |
|---|---|
| All keys are valid identifiers | Class syntax |
| Hyphens, dots, `@` or leading digits in keys | Functional syntax |
| Keys that are Python keywords | Functional syntax |
| Mixture of awkward and ordinary keys | Functional base, class-syntax subclass |
| Fields built dynamically at runtime | Neither. Use plain `dict` or a validation library. |
Summary
- Use
Name = TypedDict("Name", {"key": type, ...})when a key is not a valid Python identifier. total=False,RequiredandNotRequiredwork in the functional form.- Subclass a functional
TypedDictwith the class syntax to add ordinary keys. - The string name must match the variable, and the fields must be a literal dictionary.
- Do not use the removed keyword form
TypedDict("Name", x=int).
Exercise
A webhook payload looks like {"@type": "push", "ref": "main", "pusher.name": "ada", "class": "fast"}. Define a functional TypedDict called Webhook in which "@type" is restricted to the literal "push", "ref" and "pusher.name" are required strings, and "class" is an optional string. Which syntax do you need, and why?
Show answer
Use the functional syntax, because "@type", "pusher.name" and "class" cannot be class attribute names. For example: Webhook = TypedDict("Webhook", {"@type": Literal["push"], "ref": str, "pusher.name": str, "class": NotRequired[str]}), with Literal and NotRequired imported from typing. Alternatively, pass total=False and wrap "@type", "ref" and "pusher.name" in Required.
Exercise
What does a type checker report for this code, and what happens when it runs? Bar = TypedDict("Foo", {"a-b": int})
Show answer
The checker reports that the first argument "Foo" does not match the variable name "Bar". At runtime the code runs without error, and the class is created with the name Foo, which makes later error messages and reprs misleading.
Exercise
You have a base type Meta = TypedDict("Meta", {"X-Trace-ID": str}). Write a class-syntax subclass Job that adds a required str key "name", then say which keys appear in Job._requiredkeys__.
Show answer
class Job(Meta): name: str. Job.requiredkeys__ contains both "X-Trace-ID" and "name", because the subclass inherits every key from the functional base together with its required status.