Skip to content

Literals should raise a more friendly error message #2160

Description

@rambleraptor

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)

Activity

  1. jayceslesar commented on Jun 29, 2025

    @jayceslesar
    Contributor

    Nice, yeah looks like we can do something like

    from typing import Any, Literal
    
    from pydantic import BaseModel, Field, field_validator
    
    
    class MyModel(BaseModel):
        my_literal: Literal[1] = Field(alias="my-literal")
    
        @field_validator("my_literal", mode="before")
        def validate_my_literal(cls, v: Any) -> int:
            """Validate that my_literal is 1 for MyModel."""
            if v != 1:
                raise ValueError(f"MyModel requires my-literal to be 1, got {v}")
            return v
    
    MyModel(**{"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
    
  2. github-actions commented on Dec 30, 2025

    @github-actions

    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.

  3. github-actions commented on Jan 14, 2026

    @github-actions

    This issue has been closed because it has not received any activity in the last 14 days since being marked as 'stale'

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

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