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
Conversation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Deploying with Cloudflare Pages
|
please review |
adriangb
commented
Jun 15, 2023
docs/usage/types/custom.md
Outdated
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] | ||
""" | ||
``` |
There was a problem hiding this comment.
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
force-pushed
the
custom-type-docs-1
branch
from
June 15, 2023 17:57
f22d494
to
14bfdbf
Compare
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
tpdorsey
approved these changes
Jun 15, 2023
There was a problem hiding this 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.
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>
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Selected Reviewer: @Kludex