[Python] Accept enum names for parameters with Pydantic's @validate_call

Discussão em 'Python' iniciado por Stack, Fevereiro 20, 2025.

  1. Stack

    Stack Membro Participativo

    This question asks about using the name of an Enum when serializing a model. I want something like that except with the @validate_call annotation.

    Take this function foo():

    from enum import Enum
    from pydantic import validate_call

    class Direction(Enum):
    NORTH = 0
    EAST = 1
    SOUTH = 2
    WEST = 3

    @validate_call
    def foo(d: Direction):
    print(d)


    I want all of these inputs to work:

    >>> foo(0)
    Direction.NORTH
    >>> foo(Direction.EAST)
    Direction.EAST
    >>> foo('WEST')
    Direction.WEST
    >>> foo(' sOUtH ') # This would be great though not essential
    Direction.SOUTH


    What's the simplest way to do this?

    If it requires creating a function used as a BeforeValidator, I'd prefer that that function be generic. I have many fooss and many enums, and I don't want a separate validator for handling each one. (At that point, it's easier to validate the type within the function itself instead of using Pydantic).

    Continue reading...

Compartilhe esta Página