diff --git a/docs/examples/models_from_typeddict.py b/docs/examples/models_from_typeddict.py new file mode 100644 index 0000000000..54136274e9 --- /dev/null +++ b/docs/examples/models_from_typeddict.py @@ -0,0 +1,21 @@ +from typing import TypedDict + +from pydantic import ValidationError, create_model_from_typeddict + + +class User(TypedDict): + name: str + id: int + + +class Config: + extra = 'forbid' + + +UserM = create_model_from_typeddict(User, __config__=Config) +print(repr(UserM(name=123, id='3'))) + +try: + UserM(name=123, id='3', other='no') +except ValidationError as e: + print(e) diff --git a/docs/usage/models.md b/docs/usage/models.md index 87312469db..062808f6f5 100644 --- a/docs/usage/models.md +++ b/docs/usage/models.md @@ -384,6 +384,18 @@ You can also add validators by passing a dict to the `__validators__` argument. {!.tmp_examples/models_dynamic_validators.py!} ``` +## Model creation from `NamedTuple` or `TypedDict` + +Sometimes you already use in your application classes that inherit from `NamedTuple` or `TypedDict` +and you don't want to duplicate all your information to have a `BaseModel`. +For this _pydantic_ provides `create_model_from_namedtuple` and `create_model_from_typeddict` methods. +Those methods have the exact same keyword arguments as `create_model`. + + +```py +{!.tmp_examples/models_from_typeddict.py!} +``` + ## Custom Root Types Pydantic models can be defined with a custom root type by declaring the `__root__` field.