How to limit choices for pydantic using Enum

Viewed 1471

I got next Enum options:

class ModeEnum(str, Enum):
""" mode """

    map = "map"
    cluster = "cluster"
    region = "region"

This enum used in two Pydantic data structures. In one data structure I need all Enum options. In other data structure I need to exclude region. If I use custom validation for this and try to enter some other value, standard Validation error message informs, that allowed values are all three.

So what is best decision in this situation?

P.S. I use map variable in ModeEnum. Is it bad? I can't imagine situation when it can override built-in map object, but still, is it ok?

1 Answers

It's a little bit of a hack, but if you mark your validator with pre=True, you should be able to force it to run first, and then you can throw a custom error with the allowed values.

Related