1

I have an Enum:

class DataType(Enum):
    TIMESTAMP = MyClass("ts")
    DATETIME = MyClass("dt")
    DATE = MyClass("date")

and a Pydantic Model with a field of the type of that Enum:

class Aggregation(BaseModel):
    field_data_type: DataType

Is there a convenient way to tell Pydantic to validate the Model field against the names of the enum rather than the values? i.e., to be able to build this Model:

agg = Aggregation(field_data_type="TIMESTAMP")
4
  • I don't know what exactly your case is, but I would say that creating 2 enums instead of 1 in a situation like this is a much better practice. It could be something like: class DataType(Enum): TIMESTAMP = "TIMESTAMP" and class DataTypeAPI(Enum): TIMESTAMP = "ts" Commented Jul 2, 2024 at 11:06
  • but I have 20 enum names, it will create unnecessary code duplication Commented Jul 2, 2024 at 15:58
  • These enums have different purposes, this is not a duplication, but a way to make your enums responsible for one thing. Any wrappers over enumerations will only confuse other developers, even if they take up a few less lines of code. Commented Jul 2, 2024 at 16:05
  • Moreover, you increase the chance of an error appearing. Of course, this is just a recommendation and the final decision is yours! Commented Jul 2, 2024 at 16:07

1 Answer 1

1

You can use the built-in functionality of Enum to accomplish this:

agg = Aggregation(field_data_type=DataType["TIMESTAMP"])

You can wrap this in a function and then create a new annotated type that calls it:

def convert_to_data_type(s: str):
    return DataType[s]

StrDataType = Annotated[str, AfterValidator(convert_to_data_type)]

class Aggregation(BaseModel):
    field_data_type: StrDataType

agg = Aggregation(field_data_type="TIMESTAMP")
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.