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

Relax signature checks to better support builtins and C extension functions as validators #7101

Merged
merged 3 commits into from Aug 16, 2023
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
9 changes: 6 additions & 3 deletions pydantic/_internal/_decorators.py
Expand Up @@ -504,10 +504,13 @@ def inspect_validator(validator: Callable[..., Any], mode: FieldValidatorModes)
Returns:
Whether the validator takes an info argument.
"""
if getattr(validator, '__module__', None) == 'builtins':
# int, str, etc.
try:
sig = signature(validator)
except ValueError:
# builtins and some C extensions don't have signatures
# assume that they don't take an info argument and only take a single argument
# e.g. `str.strip` or `datetime.datetime`
return False
sig = signature(validator)
n_positional = count_positional_params(sig)
if mode == 'wrap':
if n_positional == 3:
Expand Down
6 changes: 5 additions & 1 deletion tests/test_validators.py
Expand Up @@ -61,11 +61,15 @@ class Model(BaseModel):
def test_annotated_validator_builtin() -> None:
"""https://github.com/pydantic/pydantic/issues/6752"""
TruncatedFloat = Annotated[float, BeforeValidator(int)]
DateTimeFromIsoFormat = Annotated[datetime, BeforeValidator(datetime.fromisoformat)]

class Model(BaseModel):
x: TruncatedFloat
y: DateTimeFromIsoFormat

assert Model(x=1.234).x == 1
m = Model(x=1.234, y='2011-11-04T00:05:23')
assert m.x == 1
assert m.y == datetime(2011, 11, 4, 0, 5, 23)


def test_annotated_validator_plain() -> None:
Expand Down