Search code examples
pythonpydantic

Pydantic ConfigDict(use_enum_values=True) has no effect when providing default value. How can I provide default values?


The following is a simplified example.

I need to configure ConfigDict(use_enum_values=True) as the code performs model_dump(), and I want to get rid of raw enum values for the purpose of later serialization.

How can A provide a default value for A.x, so that model_dump() outputs the enum value and not the enum itself?

Bonus: Is there any way for A to initilize A.x itself and make it impossible for users to set it? After all, default values can be overriden

from enum import Enum
from pydantic import BaseModel, ConfigDict

class X(Enum):
   x = "X"
   y = "Y"
   z = "Z"

class A(BaseModel):
   model_config = ConfigDict(use_enum_values=True, frozen=True)
   x: X = X.x

>>> A()
A(x=<X.x: 'X'>)

>>> A(x=X.x)
A(x='X')

Solution

  • You can use the validate_default config option to validate the default values as well. See:

    from enum import Enum
    from pydantic import BaseModel, ConfigDict
    
    class X(Enum):
        x = "X"
        y = "Y"
        z = "Z"
    
    class A(BaseModel):
        model_config = ConfigDict(
            use_enum_values=True,
            frozen=True,
            validate_default=True,
        )
        x: X = X.x
    

    Which now outputs:

    >>> A()
    A(x='X')
    

    I hope this helps!