Search code examples
pythonenumspydantic

Pydantic Enum class validator


I have this enum class which checks for boolean values:

class MyEnumClass(int, Enum): 
    true = 1
    false = 0

I have 134 Pydantic Models (I am using Pydantic1); each of them has several fields validated through this enum class.

I realized that when I am going to do MyPydanticModel.my_boolean_field the result is not 1 or 0 but MyEnumClass.true or MyEnumClass.false.

To face that, I was thinking to create in each pydantic Model this method:

@validator('first_boolean_field', 'second_boolean_field','....','last_boolean_field')
@classmethod
def get_boolean_value(cls, val):
    return val.value

It seems ridiculous to me to create 134 methods to do the same thing; is there a way to create a method in the enum class so that PydanticModel.boolean_field returns the real value?


Solution

  • I think you are looking for the use_enum_values option. Take a look at the following example:

    from enum import Enum
    from pydantic import BaseModel
    
    
    class MyEnumClass(int, Enum): 
        true = 1
        false = 0
    
    
    class MyModel(BaseModel):
        class Config:
            use_enum_values = True
    
        a: MyEnumClass
        b: MyEnumClass
    
    m = MyModel(a=1, b=0)
    
    print(m.a)
    print(m.b)
    

    Which prints 1 and 0.

    I hope this helps!