-
-
Notifications
You must be signed in to change notification settings - Fork 2.3k
Open
Labels
Description
Initial Checks
- I have searched Google & GitHub for similar requests and couldn't find anything
- I have read and followed the docs and still think this feature is missing
Description
When using an Optional type hint, the Pydantic ValidationError does not mention that "None" is valid.
from typing import Literal, Optional
from pydantic import BaseModel
class Settings(BaseModel):
sample: Optional[Literal["test1", "test2"]]
Settings(sample=2)ValidationError: 1 validation error for Settings
sample
Input should be 'test1' or 'test2' [type=literal_error, input_value=2, input_type=int]
For further information visit https://errors.pydantic.dev/2.5/v/literal_error
From a user's perspective, this can be confusing because sample doesn't only take "test" or "test2" as inputs but also None, and this is not mentioned in the returned ValidationError.
Affected Components
- Compatibility between releases
- Data validation/parsing
- Data serialization -
.model_dump()and.model_dump_json() - JSON Schema
- Dataclasses
- Model Config
- Field Types - adding or changing a particular data type
- Function validation decorator
- Generic Models
- Other Model behaviour -
model_construct(), pickling, private attributes, ORM mode - Plugins and integration with other tools - mypy, FastAPI, python-devtools, Hypothesis, VS Code, PyCharm, etc.