Skip to content

Commit

Permalink
docs: add section for create_model_from_{namedtuple,typeddict}
Browse files Browse the repository at this point in the history
  • Loading branch information
PrettyWood committed Jan 17, 2021
1 parent 3361496 commit d737f07
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 0 deletions.
21 changes: 21 additions & 0 deletions 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)
12 changes: 12 additions & 0 deletions docs/usage/models.md
Expand Up @@ -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.
Expand Down

0 comments on commit d737f07

Please sign in to comment.