Skip to content

Enum field validation fallback #2468

Discussion options

You must be logged in to vote

Hi @dwbelliston
IMO the best way is to overwrite _missing_ in your Enum like this

from enum import Enum, auto

from pydantic import BaseModel


class Fruit(Enum):
    APPLE = auto()
    PEAR = auto()

    @classmethod
    def _missing_(cls, value):
        return cls.APPLE


class Model(BaseModel):
    fruit: Fruit

print(Model(fruit=Fruit.APPLE).fruit)  # Fruit.APPLE
print(Model(fruit=Fruit.PEAR).fruit)  # Fruit.PEAR
print(Model(fruit='invalid').fruit)  # Fruit.APPLE

Hope it helps!

Replies: 1 comment 1 reply

Comment options

You must be logged in to vote
1 reply
@dwbelliston
Comment options

Answer selected by dwbelliston
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
2 participants