Sub topic 6
What happens at runtime: plain dicts and no validation
This chapter assumes you can read type hints, know that mypy or pyright check annotations separately from running the code, and have defined a TypedDict as in the earlier chapters.
A TypedDict is a dict
Calling a TypedDict class does not build a special object. It returns an ordinary dict. The class exists for the type checker and for introspection, not to change how dictionaries behave.
from typing import TypedDict, get_type_hints
class Point(TypedDict):
x: int
y: int
p = Point(x=1, y=2)
print(type(p))
print(isinstance(p, dict))
print(get_type_hints(Point))
print(sorted(Point.__required_keys__))
bad: Point = {"x": "not an int", "y": 2} # flagged by a type checker, runs without errorThe program prints this:
<class 'dict'>
True
{'x': <class 'int'>, 'y': <class 'int'>}
['x', 'y']The last line assigns a string to x. Python accepts it, because nothing checks the value. Only a static checker reports the error.
Two views of the same code
The diagram shows why the same file can pass one tool and misbehave in another.
What you can inspect at runtime
The class keeps metadata that you can read:
get_type_hints(Point)returns the annotation for each key.Point.__required_keys__andPoint.__optional_keys__are frozensets of key names.Point.__annotations__holds the raw annotations.
Frameworks and tools use this metadata to build validators, schemas or documentation. The metadata describes the intended shape. It does not enforce it.
What does not work at runtime
You cannot use a TypedDict class with isinstance. Python raises an error instead of guessing:
from typing import TypedDict
class Point(TypedDict):
x: int
y: int
try:
isinstance({"x": 1, "y": 2}, Point)
except TypeError as exc:
print(exc)To test whether an object is a dictionary, check against dict. To test whether it has the right keys and value types, write the check yourself or use a validation library.
Literal is not enforced either
Literal behaves the same way. The call below passes a value the checker would reject, and Python runs it:
from typing import Literal
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") # rejected by a type checker, still runs normallyCommon errors
- Assuming a bad value raises an error. It does not. Add a check at the boundary where data enters your program.
- Using
isinstancewith a TypedDict. It raisesTypeError. Check againstdict, then check keys and values yourself. - Treating a clean checker run as proof of valid data. The checker proves your code is consistent with the declared shape. It says nothing about what arrives at runtime.
- Expecting methods or defaults. A TypedDict instance has only the methods of
dict. It has no constructor logic beyond building a dict.
Exercise
A function is annotated def load(raw: str) -> Point: and returns json.loads(raw), where Point is a TypedDict with int keys x and y. The input is '{"x": "oops"}'. Does the checker report a problem, does Python raise an error at the return statement, and where would you add a check?
Show answer
The checker does not report a problem, because json.loads returns Any, which is accepted as Point. Python does not raise at the return, since nothing validates the dict. The error appears only later, when code reads y (a KeyError) or does arithmetic on x (a TypeError). Add the check inside load, before returning: confirm the keys exist and the values are ints, or use a validation library.