-
-
Notifications
You must be signed in to change notification settings - Fork 1.7k
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
Enforce constraints on arbitrary types via functional validators #5883
Conversation
Deploying with Cloudflare Pages
|
please review |
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.
otherwise LGTM.
pydantic/_internal/_validators.py
Outdated
|
||
def greater_than_validator(x: Any, gt: Any) -> Any: | ||
if not (x > gt): | ||
raise PydanticCustomError('greater_than', 'Input should be greater than {gt}', {'gt': gt}) |
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.
raise PydanticCustomError('greater_than', 'Input should be greater than {gt}', {'gt': gt}) | |
raise PydanticKnownError('greater_than', {'gt': gt}) |
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.
Won't work:
def greater_than_validator(x: Any, gt: Any) -> Any:
if not (x > gt):
> raise PydanticKnownError('greater_than', {'gt': gt})
E TypeError: GreaterThan: 'gt' context value must be a Number
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.
needs to be fixed in core, bit this is fine for now.
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.
I hadn't realised it was every single one that was using PydanticCustomError
, we should adopt PydanticKnownError
where possible.
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.
Unless I’m missing something, you already pointed that out and as per above, it won’t work unless we make extensive changes in pydantic-core. It also makes no difference for users as far as I can tell.
c7252b4
to
27f476f
Compare
27f476f
to
4befd4f
Compare
This makes constraints work on arbitrary types that don't "know" how to consume them by applying a functional validator that enforces the constraint in Python. Of course, if the type wants to it can "consume" the constraint via
__prepare_pydantic_annotations__
to e.g. use a more efficient implementation, or if the schema is a schema that accepts the constraint directly (e.g.gt
w/ afloat
schema) then it gets applied that way instead of via Python.Selected Reviewer: @dmontagu