Как я могу прикрепить документацию к членам перечисления python? - PullRequest
0 голосов
/ 22 мая 2018

Я хотел бы предоставить документацию для каждого члена перечисления python таким образом, чтобы IPython мог его найти.Сейчас у меня есть что-то вроде:

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 ]

0 голосов
/ 22 мая 2018

@ Эрик показал , как это сделать с помощью stdlib Enum;Вот как это сделать, используя 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 Enum, enum34 backport и Advanced Enumeration (aenum) library.

0 голосов
/ 22 мая 2018

Вы можете переопределить 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"

, который в IPython дает следующее:

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
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...