Skip to content

Commit

Permalink
Add typing.Annotated docs
Browse files Browse the repository at this point in the history
  • Loading branch information
JacobHayes committed Dec 26, 2020
1 parent 97b8d31 commit 74740b9
Show file tree
Hide file tree
Showing 3 changed files with 33 additions and 0 deletions.
13 changes: 13 additions & 0 deletions docs/examples/schema_annotated.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
from uuid import uuid4

try:
from typing import Annotated
except ImportError:
from typing_extensions import Annotated

from pydantic import BaseModel, Field


class Foo(BaseModel):
id: Annotated[str, Field(default_factory=lambda: uuid4().hex)]
name: Annotated[str, Field(max_length=256)] = 'Bar'
15 changes: 15 additions & 0 deletions docs/usage/schema.md
Original file line number Diff line number Diff line change
Expand Up @@ -106,6 +106,21 @@ to `Field()` with the raw schema attribute name:
```
_(This script is complete, it should run "as is")_

### typing.Annotated Fields

Rather than assigning a `Field` value, it can be specified in the type hint with `typing.Annotated`:

```py
{!.tmp_examples/schema_annotated.py!}
```
_(This script is complete, it should run "as is")_

`Field` can only be supplied once per field - an error will be raised if used in `Annotated` and as the assigned value.
Defaults can be set outside `Annotated` as the assigned value or with `Field.default_factory` inside `Annotated` - the
`Field.default` argument is not supported inside `Annotated`.

For versions of Python prior to 3.9, `typing_extensions.Annotated` can be used.

## Modifying schema in custom fields

Custom field types can customise the schema generated for them using the `__modify_schema__` class method;
Expand Down
5 changes: 5 additions & 0 deletions docs/usage/types.md
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,11 @@ with custom properties and validation.
`typing.Any`
: allows any value include `None`, thus an `Any` field is optional

`typing.Annotated`
: allows wrapping another type with arbitrary metadata, as per [PEP-593](https://www.python.org/dev/peps/pep-0593/). The
`Annotated` hint may contain a single call to the [`Field` function](schema.md#typingannotated-fields), but otherwise
the additional metadata is ignored and the root type is used.

`typing.TypeVar`
: constrains the values allowed based on `constraints` or `bound`, see [TypeVar](#typevar)

Expand Down

0 comments on commit 74740b9

Please sign in to comment.