代码之家  ›  专栏  ›  技术社区  ›  Eric

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

  •  6
  • Eric  · 技术社区  · 8 年前

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

    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
    

    这并不是很好,因为它复制了成员名称,并且使仅为一个成员索要文档变得更加困难。

    我可以得到我想要的东西

    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"
    

    但这仍然会受到名字重复的影响。

    有更简单的方法吗?

    2 回复  |  直到 8 年前
        1
  •  5
  •   Ethan Furman    7 年前

    您可以覆盖 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
    

    可用于:

    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 :

    class DocIntEnum(IntEnum):
        def __new__(cls, value, doc=None):
            self = int.__new__(cls, value)  # calling super().__new__(value) here would fail
            self._value_ = value
            if doc is not None:
                self.__doc__ = doc
            return self
    
        2
  •  3
  •   Ethan Furman    7 年前

    @埃里克展示了 how to do it 使用stdlib Enum ;这是如何使用 aenum :

    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'
    

    披露:我是 Python stdlib Enum , the enum34 backport Advanced Enumeration ( aenum ) 图书馆。