如何将文档附加到python枚举的成员?

时间:2018-05-22 18:06:15

标签: python enums

我想以一种IPython可以找到它的方式为python枚举的每个成员提供文档。我现在所拥有的是:

SELECT cht_name FROM ers_chapters
RIGHT JOIN ers_subjects ON ers_chapters.cht_sub_id = $sub_id
GROUP BY cht_name

这不是很好,因为它复制了成员名称,并且更难要求只有一个成员的文档。

我可以得到我所追求的

class Color(Enum):
    """
    RED: The color red
    GREEN: The color green
    BLUE: The color blue. These docstrings are more useful in the real example
    """
    RED = 1
    GREEN = 2
    BLUE = 3

但这仍然会因重复这些名字而受到影响。

有更简单的方法吗?

2 个答案:

答案 0 :(得分:5)

您可以覆盖class Color(Enum): RED = 1 GREEN = 2 BLUE = 3 Color.RED.__doc__ = "The color red" Color.GREEN.__doc__ = "The color green" Color.BLUE.__doc__ = "The color blue. These docstrings are more useful in the real example" 以获取Enum.__new__参数,如下所示:

doc

可以用作:

class DocEnum(Enum):
    def __new__(cls, value, doc=None):
        self = object.__new__(cls)  # calling super().__new__(value) here would fail
        self._value_ = value
        if doc is not None:
            self.__doc__ = doc
        return self

在IPython中,提供以下内容:

class Color(DocEnum):
    """ Some colors """
    RED   = 1, "The color red"
    GREEN = 2, "The color green"
    BLUE  = 3, "The color blue. These docstrings are more useful in the real example"

这也适用于In [17]: Color.RED? Type: Color String form: Color.RED Docstring: The color red Class docstring: Some colors

IntEnum

答案 1 :(得分:3)

@Eric使用stdlib Enum显示how to do it;这是使用aenum 1

的方法
from aenum import Enum  # or IntEnum


class Color(Enum):                     # or IntEnum

    _init_ = 'value __doc__'

    RED = 1, 'The color red'
    GREEN = 2, 'The color green'
    BLUE = 3, 'The color blue'

1 披露:我是Python stdlib Enumenum34 backportAdvanced Enumeration (aenum)图书馆的作者。