[Python] Pydantic restrict string to literal values and convert to lower case

Discussão em 'Python' iniciado por Stack, Março 26, 2025.

  1. Stack

    Stack Membro Participativo

    How can I restrict the value of a string field to certain values in a case insensitive way?

    >>> Animal(species="antelope")
    >>> Animal(species="AnTeLoPe")
    >>> Animal(species="frog") # ValidationError: `species must be antelope or zebra`


    I know that you can restrict a Pydantic field to certain values:

    import pydantic
    from typing import Literal


    class Animal(pydantic.BaseModel):
    species: Literal["antelope", "zebra"]


    And I know that you can convert input data to lowercase:

    class Animal(pydantic.BaseModel):
    species: pydantic.constr(to_lower=True)


    But I can't see how I would combine these two features so I don't have to spell out the upper-case and lower-case versions of my set of literals:

    class Animal(pydantic.BaseModel):
    species: Literal["antelope", "Antelope"] # ...etc


    I thought using str_to_lower would help, but it doesn't work:

    class Animal(pydantic.BaseModel):
    model_config = pydantic.ConfigDict(str_to_lower=True)
    species: Literal["antelope", "zebra"]

    Animal(species="AnTeLope") # ValidationError


    I can see a way out of this with regex, but it seems like this is such a common use-case that using regex seems like an inconvenient workaround (what if my allowed values have got regex-ish characters? then I have to escape them)

    Continue reading...

Compartilhe esta Página