You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Literals should raise a more friendly error message #2160
We should find a way to make sure that incorrect Literals raise a friendlier error message than the standard Pydantic error message. Pydantic might be able to do this for us.
fromtypingimportAny, LiteralfrompydanticimportBaseModel, Field, field_validatorclassMyModel(BaseModel):
my_literal: Literal[1] =Field(alias="my-literal")
@field_validator("my_literal", mode="before")defvalidate_my_literal(cls, v: Any) ->int:
"""Validate that my_literal is 1 for MyModel."""ifv!=1:
raiseValueError(f"MyModel requires my-literal to be 1, got {v}")
returnvMyModel(**{"my-literal": 2})
Which raises
pydantic_core._pydantic_core.ValidationError: 1 validation error for MyModel
my-literal
Value error, MyModel requires my-literal to be 1, got 2 [type=value_error, input_value=2, input_type=int]
For further information visit https://errors.pydantic.dev/2.11/v/value_error
This issue has been automatically marked as stale because it has been open for 180 days with no activity. It will be closed in next 14 days if no further activity occurs. To permanently prevent this issue from being considered stale, add the label 'not-stale', but commenting on the issue is preferred when possible.
We should find a way to make sure that incorrect Literals raise a friendlier error message than the standard Pydantic error message. Pydantic might be able to do this for us.
Context: #2154 (comment)