Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commitde217f4

Browse files
authored
ImprovePlainValidator example (#11954)
1 parentbcd10f7 commitde217f4

File tree

2 files changed

+9
-5
lines changed

2 files changed

+9
-5
lines changed

‎docs/migration.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -447,7 +447,7 @@ However, in Pydantic V2, when a `TypeError` is raised in a validator, it is no l
447447
```python
448448
import pytest
449449

450-
from pydanticimport BaseModel, field_validator# or validator
450+
from pydanticimport BaseModel, field_validator
451451

452452

453453
classModel(BaseModel):

‎pydantic/functional_validators.py

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -174,11 +174,15 @@ class PlainValidator:
174174
175175
from pydantic import BaseModel, PlainValidator
176176
177+
def validate(v: object) -> int:
178+
if not isinstance(v, (int, str)):
179+
raise ValueError(f'Expected int or str, go {type(v)}')
180+
181+
return int(v) + 1
182+
177183
MyInt = Annotated[
178184
int,
179-
PlainValidator(
180-
lambda v: int(v) + 1, json_schema_input_type=Union[str, int] # (1)!
181-
),
185+
PlainValidator(validate, json_schema_input_type=Union[str, int]), # (1)!
182186
]
183187
184188
class Model(BaseModel):
@@ -192,7 +196,7 @@ class Model(BaseModel):
192196
```
193197
194198
1. In this example, we've specified the `json_schema_input_type` as `Union[str, int]` which indicates to the JSON schema
195-
generator that in validation mode, the input type for the `a` field can be either a `str` or an `int`.
199+
generator that in validation mode, the input type for the `a` field can be either a[`str`][] or an[`int`][].
196200
"""
197201

198202
func:core_schema.NoInfoValidatorFunction|core_schema.WithInfoValidatorFunction

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp