Skip to content

String-to-integer coercion doesn't work with a Literal[int...] type #11889

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
DouweM opened this issue May 19, 2025 · 2 comments
Open

String-to-integer coercion doesn't work with a Literal[int...] type #11889

DouweM opened this issue May 19, 2025 · 2 comments

Comments

@DouweM
Copy link
Contributor

DouweM commented May 19, 2025

As reported on pydantic/pydantic-ai#1691:

from typing import Annotated, Literal

from pydantic import BaseModel, Field

class Dice(BaseModel):
    result: Annotated[Literal[1, 2, 3, 4, 5, 6], Field(description="The result of a 1d6")] | None = None

Dice.model_validate({"result":"1"})
pydantic_core._pydantic_core.ValidationError: 1 validation error for Dice
result
  Input should be 1, 2, 3, 4, 5 or 6 [type=literal_error, input_value='1', input_type=str]
    For further information visit https://errors.pydantic.dev/2.10/v/literal_error
@Viicos
Copy link
Member

Viicos commented May 20, 2025

We got a similar report here: #9991.

I think we should provide a way to do so, perhaps with a new metadata to indicate that you want "non-strict" behavior.

@DouweM
Copy link
Contributor Author

DouweM commented May 20, 2025

@Viicos What's the concern with making this the out of the box behavior? That issue says it was rejected by the team because literals "should" be strict, but it's not clear to me why we don't see this as equivalent to the following, where the coercion does work:

class Dice(BaseModel):
    result: Annotated[int, Field(description="The result of a 1d6", ge=1, le=6)] | None = None

I think of the https://en.wikipedia.org/wiki/Robustness_principle, "be conservative in what you send, be liberal in what you accept", and don't see a downside to losslessly coercing strings to ints.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy