instructor
42 строки · 1.2 Кб
1from pydantic import BaseModel, ValidationError, field_validator2
3
4class UserDetail(BaseModel):5age: int6name: str7
8@field_validator("name", mode="before")9def name_must_contain_space(cls, v):10"""11This validator will be called after the default validator,
12and will raise a validation error if the name does not contain a space.
13then it will set the name to be lower case
14"""
15if " " not in v:16raise ValueError("name be a first and last name separated by a space")17return v.lower()18
19
20# Example 1) Valid input, notice that the name is lowercased
21person = UserDetail(age=29, name="Jason Liu")22print(person.model_dump_json(indent=2))23"""
24{
25"age": 29,
26"name": "jason liu"
27}
28"""
29
30# Example 2) Invalid input, we'll get a validation error
31# In the future this validation error will be raised by the API and
32# used by the LLM to generate a better response
33try:34person = UserDetail(age=29, name="Jason")35except ValidationError as e:36print(e)37"""381 validation error for UserDetail
39name
40Value error, must contain a space [type=value_error, input_value='Jason', input_type=str]
41For further information visit https://errors.pydantic.dev/2.3/v/value_error
42"""
43