Sub topic 6
What happens at runtime: plain dicts and no validation
This chapter assumes you can write Python classes and functions and have used basic type hints. It also assumes you know that a checker such as mypy or pyright reads your annotations separately from the interpreter that runs your code. The previous chapters covered the static side of TypedDict and Literal. This chapter covers what the interpreter does with them.
A TypedDict instance is a plain dict
Calling a TypedDict class looks like creating an object. At runtime it only builds a dictionary.
from typing import TypedDict, is_typeddict
class Point(TypedDict):
x: int
y: int
p = Point(x=1, y=2)
print(type(p))
print(p == {"x": 1, "y": 2})
print(is_typeddict(Point))
try:
isinstance(p, Point)
except TypeError as exc:
print(exc)The output is:
<class 'dict'>
True
True
TypedDict does not support instance and class checksPoint(x=1, y=2) returns an ordinary dict. No Point object exists at runtime. This has three consequences.
type(p)isdict, andpequals any dict with the same keys and values.isinstance(p, Point)andissubclass(...)raiseTypeError. Useisinstance(p, dict)to test the container, and your own checks for its shape.is_typeddict(Point)tells you whether a class was built withTypedDict. It says nothing about a given dictionary.
Nothing is validated
Because the instance is a plain dict, the interpreter accepts everything a checker would reject.
| Operation | Type checker | Runtime |
|---|---|---|
| `Point(x=1)` (missing `y`) | Reports an error | Works |
| `Point(x="a", y=2)` (wrong value type) | Reports an error | Works |
| `Point(x=1, y=2, z=3)` (extra key) | Reports an error | Works |
| `del p["x"]` (removing a required key) | Reports an error | Works |
| `isinstance(p, Point)` | Reports an error | Raises `TypeError` |
A checker validates the dictionaries your own code builds. It cannot know what is inside data that arrives from outside, such as a parsed JSON document. For example, json.loads is declared to return Any, so a checker accepts any annotation you assign to its result.
import json
from typing import TypedDict
class Point(TypedDict):
x: int
y: int
data: Point = json.loads('{"x": "oops", "y": 2}')
print(data["x"] + 1)A checker sees nothing wrong with this file. At runtime it fails with TypeError: can only concatenate str (not "int") to str. The error appears far from the real cause, which is untrusted data that was annotated as if it were already checked.
Literal is not enforced either
Literal behaves the same way. The interpreter does not compare the argument with the allowed values.
from typing import Literal, get_args, get_origin
Mode = Literal["r", "w", "a"]
def open_log(path: str, mode: Mode) -> None:
print(f"opening {path} with mode {mode}")
open_log("app.log", "x")
print(get_origin(Mode) is Literal)
print(get_args(Mode))The output is:
opening app.log with mode x
True
('r', 'w', 'a')The call with "x" is flagged by a checker and runs without complaint. The alias keeps its allowed values, though, and get_args returns them. That is what makes it possible to build a runtime check from the same definition.
What you can inspect at runtime
A TypedDict class keeps metadata that you can read.
from typing import NotRequired, TypedDict, get_type_hints
class User(TypedDict):
id: int
name: str
email: NotRequired[str]
print(sorted(User.__required_keys__))
print(sorted(User.__optional_keys__))
print(User.__total__)
print(get_type_hints(User))
print(get_type_hints(User, include_extras=True))The output is:
['id', 'name']
['email']
True
{'id': <class 'int'>, 'name': <class 'str'>, 'email': <class 'str'>}
{'id': <class 'int'>, 'name': <class 'str'>, 'email': typing.NotRequired[str]}| Attribute or function | What it gives you |
|---|---|
| `__required_keys__` | A `frozenset` of keys that must be present |
| `__optional_keys__` | A `frozenset` of keys that may be missing |
| `__total__` | The `total=` setting of the class itself |
| `get_type_hints(cls)` | Resolved types, with `Required`, `NotRequired` and `ReadOnly` wrappers removed |
| `get_type_hints(cls, include_extras=True)` | The same, with those wrappers kept |
| `__annotations__` | The raw annotations, possibly unresolved strings |
The two key sets are frozenset objects, which have no stable order. Sort them when you print them or compare output.
Building a runtime check from the metadata
The metadata is enough for a small validator for flat TypedDict classes. It reports problems instead of raising on the first one.
from typing import Any, Literal, TypedDict, get_args, get_origin, get_type_hints
class Job(TypedDict):
name: str
retries: int
mode: Literal["r", "w"]
def check(value: object, cls: Any) -> list[str]:
if not isinstance(value, dict):
return ["not a dict"]
errors: list[str] = []
hints = get_type_hints(cls)
for key in sorted(cls.__required_keys__):
if key not in value:
errors.append(f"{key}: missing key")
for key, item in value.items():
if key not in hints:
errors.append(f"{key}: unexpected key")
continue
expected = hints[key]
if get_origin(expected) is Literal:
if item not in get_args(expected):
errors.append(f"{key}: {item!r} not in {get_args(expected)}")
elif not isinstance(item, expected):
errors.append(
f"{key}: expected {expected.__name__}, got {type(item).__name__}"
)
return errors
data = {"name": "build", "retries": "3", "mode": "x", "extra": 1}
for problem in check(data, Job):
print(problem)The output is:
retries: expected int, got str
mode: 'x' not in ('r', 'w')
extra: unexpected keyThis version handles only simple classes. It does not handle nested TypedDict values, generic types such as list[int], unions, or inheritance with unresolved string annotations. It also has a Python quirk: isinstance(True, int) is True, so a boolean passes as an int. Extending it to cover every case is the point where a validation library becomes the better choice, which the last chapter of this tutorial compares.
Edge cases and common errors
- Missing keys fail late.
Point(x=1)succeeds, and theKeyErrorappears only when some code readsp["y"]. WithNotRequiredkeys, usep.get("email")or test"email" in pfirst. - Extra keys survive. A checker treats an extra key as an error. At runtime the key stays in the dict and passes through
json.dumpsandcopylike any other. ATypedDictdoes not filter its input. dict(...)andcopy()return plain dicts. Copying a typed dict gives you something the checker may no longer see as the same type. Annotate the result explicitly, or usep.copy(), which checkers understand forTypedDict.- Mutation is unchecked.
p["x"] = "text"runs. The checker reports it only in code it can see. - Annotations on locals are not stored. Writing
bad: Point = {...}inside a function leaves no runtime trace at all. Only the class definition carries metadata.
A practical pattern: validate at the boundary
Because checking stops at the edge of your own code, put the runtime check where untrusted data enters, and let the type checker handle everything after that.
import json
from typing import TypedDict, cast
class Point(TypedDict):
x: int
y: int
def parse_point(text: str) -> Point:
raw = json.loads(text)
if not (
isinstance(raw, dict)
and isinstance(raw.get("x"), int)
and isinstance(raw.get("y"), int)
):
raise ValueError(f"not a valid point: {text}")
return cast(Point, raw)
print(parse_point('{"x": 1, "y": 2}'))The output is {'x': 1, 'y': 2}. The cast tells the checker that you have done the verification. It performs no check of its own. Every function that receives a Point afterwards can rely on the annotation.
Exercise
A function annotated def total(item: Order) -> float receives the dict {"price": "9.99"} from json.loads. Order is a TypedDict with price: float. Will a type checker report an error at the call site, will Python raise one when total is called, and what would you add to catch it earlier?
Show answer
No error from the type checker, because json.loads returns Any and Any is accepted for any annotation. Python raises nothing at the call itself, and the failure comes later inside total, for example when it does arithmetic on the string "9.99". To catch it earlier, validate the parsed data where it enters your program (a check like parse_point, or a validation library) and only then treat it as an Order.
Exercise
Why does isinstance(movie, Movie) raise TypeError for a TypedDict class Movie, and what can you check instead?
Show answer
At runtime movie is an ordinary dict, and Movie is a special class that exists only to hold annotations, so the interpreter refuses instance and class checks against it. You can check isinstance(movie, dict), and compare its keys and value types with Movie.__required_keys__, Movie.__optional_keys__ and get_type_hints(Movie), or use a validation library.