Pydantic json 自定义枚举上的值为空

Pydantic json value is empty on Custom Enum

我正在使用 Pydantic,我希望我的枚举也有文档字符串。

当我使用 enum.EnumCookingModel 工作正常。

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()

将return: {"fruit": "banana"}

但是当我将 enum.Enum 更改为 DocEnum(这样我就可以获得文档字符串)。

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

它将return: {"fruit": ""}

我该如何解决?

value 作为第二个参数传递给 str.__new__ 解决问题。

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'