我正在使用 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.Enum
为DocEnum
(所以我可以获得文档字符串)。
class FruitEnum(str, DocEnum):
pear = 'pear'
banana = 'banana'
它将返回:
{"fruit": ""}
我该如何解决?