How to access docstrings of enum-values in Python?

95 views Asked by At

For a code documentation tool, I want to analyze a Python Enum class and print its details. Docstrings of the individual enum values shall be printed, as well.

However, as Enum values appear as their Enum class, i.e., type(Colors.RED) -> <enum 'Colors'>, they present the __doc__ string of the Enum class "Colors we know..." rather than the expected docstring of the value: "The red color".

Here is a minimal example:

from enum import Enum

class Colors(Enum):
    """Colors we know..."""

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

for color in Colors:
    print(color.name, "->", color.__doc__)

This leads to

RED -> Colors we know...
GREEN -> Colors we know...
BLUE -> Colors we know...

However, I would like to see

RED -> The red color
GREEN -> The gree color
BLUE -> The blue color

I found some explanations hinting that this is not possible at all, e.g., https://peps.python.org/pep-0258/#attribute-docstrings.

However, there are some documents that tell me that there is the option to add docstrings to enum values, e.g., How do I put docstrings on Enums?, and -- obviously -- IDEs are able to process them.

Are those intellisense tools really parsing the code themselves to do the trick?

How can I do this?

1

There are 1 answers

1
AudioBubble On

One way to achieve what you want without relying on static code analysis tools is to use a different data structure, such as a dictionary, to store your color information. You can then use the enum names as keys in the dictionary. Here's an example of how you could do it:

class Colors:
    RED = 1
    GREEN = 2
    BLUE = 3

color_info = {
    Colors.RED: "The red color",
    Colors.GREEN: "The green color",
    Colors.BLUE: "The blue color"
}

for color in Colors:
    print(color.name, "->", color_info[color])

In this approach, you define a separate dictionary color_info that maps enum members to their respective docstrings. This way, you can easily access the docstrings without relying on the behavior of enum docstrings.