Like attrs, but for dicts
What it can do:
- Generate TypedDict from pydantic models, attrs schemas, and dataclasses.
- Validate dicts using TypedDict at runtime.
Why it's cool:
- Supports multiple schema formats.
- 100% type safe.
Install:
python3 -m pip install typed-dict
And then add in plugins
section of the mypy config (pyproject.toml
):
[tool.mypy]
plugins = ["typed_dict"]
Generate a TypedDict from a dataclass:
from dataclasses import dataclass
import typed_dict
@dataclass
class User:
name: str
age: int = 99
UserDict = typed_dict.from_dataclass(User)
Now, you can use it in type annotations (and mypy will understand it):
user: UserDict = {'name': 'aragorn'}
Or with runtime type checkers, like pydantic:
import pydantic
user = pydantic.parse_obj_as(UserDict, {'name': 'Aragorn'})
assert user == {'name': 'Aragorn'}
See examples directory for more code.