Python TypedDict
A TypedDict is a class that names the keys and value types of a dict. A checker can spot a key that is missing.
A named shape
A checker reads this shape. Your program still builds a plain dict.
from typing import TypedDict
class Config(TypedDict):
host: str
port: int
app: Config = {"host": "localhost", "port": 8000}
print(app["host"])
print(app["port"])A key that may be missing
NotRequired means the key can stay out. The other keys stay required.
from typing import NotRequired, TypedDict
class Config(TypedDict):
host: str
debug: NotRequired[bool]
app: Config = {"host": "localhost"}
print(app["host"])
print("debug" in app)Every key optional
total=False flips the whole class. Every key may stay out.
from typing import TypedDict
class Patch(TypedDict, total=False):
host: str
port: int
patch: Patch = {"port": 9000}
print(patch)
print(len(patch))Still a plain dict
At runtime, the value is just a dict. There is no special TypedDict object.
from typing import TypedDict
class Config(TypedDict):
host: str
port: int
config: Config = {"host": "localhost", "port": 8000}
print(type(config))
print(isinstance(config, dict))Example
from typing import NotRequired, TypedDict
class Config(TypedDict):
host: str
port: int
debug: NotRequired[bool]
def load_config() -> Config:
return {"host": "localhost", "port": 8000, "debug": True}
config = load_config()
print(config["host"])
print(config["port"])
print(config["debug"])
print(type(config))Key points
- TypedDict: a class that names the keys and value types of a dict
- Required key: a key the checker expects to find in the dict
- Use NotRequired[...] to mark a key that may be missing
- Use total=False to make every key in the class optional
- Use a TypedDict hint like any other hint on variables and returns
- A TypedDict value is a plain dict at runtime
In this example, Config names three keys for a settings dict. host and port are required keys. debug uses NotRequired, so it may be missing. load_config builds and returns one Config dict. The main lines read each key with normal dict syntax. The last line shows the runtime type is dict.
Note
Python adds no checks while the program runs.
Try it Yourself
Edit the code, then press Run.
Running is simulated · Python Playground
Exercise
What is a TypedDict value while the program runs?