18

I understand that I can add a Python docstring to an enum type as I would any other class. But how do I add documentation to an element of that type?

As far as I can see there are three possibilities:

class MyEnum(Enum):
    """
    This is my enum type.
    """

    """
    Variant 1
    """
    a = 0,  
    b = 1, # variant 2
    c = 2, """ variant 3 """

But none of them really work consistently. If I call print(inspect.getdoc(MyEnum.a)) in any of the variants, the docstring of the MyEnum type is returned ('This is my enum type'). Pycharm can show variant 3 in its Quick Documentation preview, but includes the quotes and longer comments that exceed the column wrap will not be shown correctly.

Is there a preferred way or convention on how to document Python enum elements?

thrau
  • 2,915
  • 3
  • 25
  • 32
  • 4
    You should be aware that tripe-quoted strings are still strings, and the commas after your values are causing them to be evaluated as tuples. Your `MyEnum.a` has value `(0,)`, and `MyEnum.c` has value `(2, ' variant 3 ')`! – Patrick Haugh Aug 28 '18 at 16:59
  • Wow thank you Patrick, I hadn't even thought of that, although it's very obvious now that you pointed it out. – thrau Aug 28 '18 at 17:01
  • What `inspect.getdoc()` is returning **is** the docstring of your `MyEnum` class, and is therefore correct due to how they are handled in Python. How you document the values is strictly how you want to do it—so there's no "proper" way to do it. – martineau Aug 28 '18 at 17:03
  • But I don't want the docstring of the type, I want that of the element. – thrau Aug 28 '18 at 17:04
  • Why not name the enum variables themselves in a self-documenting way e.g. replacing `a` with `VARIANT_A`. – Moses Koledoye Aug 28 '18 at 17:14

1 Answers1

24

If the values themselves are not important, see How do I put docstrings on Enums?. If the values are important you can either customize that answer or use the aenum1 library:

from aenum import Enum

class MyEnum(Enum):
    _init_ = 'value __doc__'
    a = 0, 'docstring for a'
    b = 1, 'another for b'
    c = 2, 'and one for c as well'

which results in:

>>> MyEnum.b.value
1
>>> MyEnum.b.__doc__
'another for b'

However, I do not know which, if any, IDEs support using Enum member doc strings.


1 Disclosure: I am the author of the Python stdlib Enum, the enum34 backport, and the Advanced Enumeration (aenum) library.

Ethan Furman
  • 63,992
  • 20
  • 159
  • 237