Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

PYD-92: Add custom type docs for Annotated and TypeAliasType #6161

Merged
merged 11 commits into from Jun 15, 2023

Conversation

adriangb
Copy link
Member

@adriangb adriangb commented Jun 15, 2023

Selected Reviewer: @Kludex

@linear
Copy link

linear bot commented Jun 15, 2023

@cloudflare-pages
Copy link

cloudflare-pages bot commented Jun 15, 2023

Deploying with  Cloudflare Pages  Cloudflare Pages

Latest commit: 7f5665a
Status: ✅  Deploy successful!
Preview URL: https://049263fc.pydantic-docs2.pages.dev
Branch Preview URL: https://custom-type-docs-1.pydantic-docs2.pages.dev

View logs

@adriangb
Copy link
Member Author

please review

Comment on lines 150 to 280
'title': 'X',
'type': 'array',
},
'y': {
'items': {'exclusiveMinimum': 0, 'type': 'integer'},
'title': 'Y',
'type': 'array',
},
},
'required': ['x', 'y'],
'title': 'Model1',
'type': 'object',
}
"""

PositiveIntList = TypeAliasType('PositiveIntList', List[Annotated[int, Gt(0)]])


class Model2(BaseModel):
x: PositiveIntList
y: PositiveIntList


print(Model2.model_json_schema())
"""
{
'$defs': {
'PositiveIntList': {
'items': {'exclusiveMinimum': 0, 'type': 'integer'},
'type': 'array',
}
},
'properties': {
'x': {'$ref': '#/$defs/PositiveIntList'},
'y': {'$ref': '#/$defs/PositiveIntList'},
},
'required': ['x', 'y'],
'title': 'Model2',
'type': 'object',
}
"""
```

#### Named recursive types

You can also use `TypeAliasType` to create recursive types:

```py
from typing import Any

from pydantic_core import PydanticCustomError
from typing_extensions import Annotated, TypeAliasType

from pydantic import (
TypeAdapter,
ValidationError,
ValidationInfo,
ValidatorFunctionWrapHandler,
WrapValidator,
)


def json_custom_error_validator(
value: Any, handler: ValidatorFunctionWrapHandler, _info: ValidationInfo
) -> Any:
"""Simplify the error message to avoid a gross error stemming
from exhaustive checking of all union options.
"""
try:
return handler(value)
except ValidationError:
raise PydanticCustomError(
'invalid_json',
'Input is not valid json',
)


Json = TypeAliasType(
'Json',
Annotated[
dict[str, 'Json'] | list['Json'] | str | int | float | bool | None,
WrapValidator(json_custom_error_validator),
],
)


ta = TypeAdapter(Json)

v = ta.validate_python({'x': [1], 'y': {'z': True}})
assert v == {'x': [1], 'y': {'z': True}}

try:
ta.validate_python({'x': object()})
except ValidationError as exc:
print(exc)
"""
1 validation error for function-wrap[json_custom_error_validator()]
Input is not valid json [type=invalid_json, input_value={'x': <object object at 0x0123456789ab>}, input_type=dict]
"""
```
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@JelleZijlstra you might find this section interesting, also thank you for your work on this!

@adriangb adriangb changed the title PYD-92: Add custom type docs for Annotated and TypeALiasType PYD-92: Add custom type docs for Annotated and TypeAliasType Jun 15, 2023
Copy link
Contributor

@tpdorsey tpdorsey left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Minor suggested edits. Looks good.

docs/usage/types/custom.md Outdated Show resolved Hide resolved
docs/usage/types/custom.md Outdated Show resolved Hide resolved
docs/usage/types/custom.md Outdated Show resolved Hide resolved
docs/usage/types/custom.md Outdated Show resolved Hide resolved
adriangb and others added 4 commits June 15, 2023 13:55
Co-authored-by: Terrence Dorsey <terrend@mishu.com>
Co-authored-by: Terrence Dorsey <terrend@mishu.com>
Co-authored-by: Terrence Dorsey <terrend@mishu.com>
Co-authored-by: Terrence Dorsey <terrend@mishu.com>
@adriangb adriangb enabled auto-merge (squash) June 15, 2023 18:56
@adriangb adriangb merged commit 5349dde into main Jun 15, 2023
51 checks passed
@adriangb adriangb deleted the custom-type-docs-1 branch June 15, 2023 19:11
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

None yet

3 participants