Pydantic json value is empty on Custom Enum

Viewed 1562

I'm working with Pydantic And I want my Enums to also have docstring.

when I use enum.Enum The CookingModel works fine.

import enum
from pydantic import BaseModel, ValidationError

class DocEnum(enum.Enum):
    """Enum with docstrings support"""

    def __new__(cls, value, doc=None):
        """add docstring to the member of Enum if exists

        Args:
            value: Enum member value
            doc: Enum member docstring, None if not exists
        """
        obj = str.__new__(cls)
        obj._value_ = value
        if doc:
            obj.__doc__ = doc
        return obj


class FruitEnum(str, enum.Enum):
    pear = 'pear'
    banana = 'banana'

class CookingModel(BaseModel):
    fruit: FruitEnum

a = CookingModel(fruit='banana')

a.json()

will return: {"fruit": "banana"}

but when I change enum.Enum to DocEnum(so I can get docstrings).

class FruitEnum(str, DocEnum):
    pear = 'pear'
    banana = 'banana'

it will return: {"fruit": ""}

how can I fix it?

1 Answers

Passing value as second argument to str.__new__ solve the problem.

import enum
from pydantic import BaseModel, ValidationError

class DocEnum(enum.Enum):
    """Enum with docstrings support"""

    def __new__(cls, value, doc=None):
        """add docstring to the member of Enum if exists

        Args:
            value: Enum member value
            doc: Enum member docstring, None if not exists
        """
        obj = str.__new__(cls, value)
        obj._value_ = value
        if doc:
            obj.__doc__ = doc
        return obj


class FruitEnum(str, DocEnum):
    pear = 'pear', 'it's pear docstring'
    banana = 'banana'
Related