2

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 Answer 1

1

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'
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.