Skip to content

A clearer ValidationError should be provided when an Optional type hint is used #8852

@Andrew-S-Rosen

Description

@Andrew-S-Rosen

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions