2

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

当我使用enum.Enum工作CookingModel正常。

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

将返回: {"fruit": "banana"}

但是当我更改enum.EnumDocEnum(所以我可以获得文档字符串)。

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

它将返回: {"fruit": ""}

我该如何解决?

4

1 回答 1

1

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'
于 2020-06-08T18:46:20.357 回答