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 4, 2020
1 parent 4135076 commit 6fd8826
Show file tree
Hide file tree
Showing 3 changed files with 30 additions and 0 deletions.
10 changes: 10 additions & 0 deletions docs/examples/schema_annotated.py
@@ -0,0 +1,10 @@
try:
from typing import Annotated
except ImportError:
from typing_extensions import Annotated

from pydantic import BaseModel, Field


class FooBar(BaseModel):
count: Annotated[int, Field(gt=-1)] = 0
15 changes: 15 additions & 0 deletions docs/usage/schema.md
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 it is used in `Annotated` and as the assigned
value. When used in `Annotated`, `Field` must not contain a default value, instead an assigned default value should be
used.

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
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 6fd8826

Please sign in to comment.