如何为Python Enum成员添加可被IPython识别的文档?
Adding Docstrings to Python Enum Members (IPython-Friendly, No Name Duplication)
Great question! The two approaches you've tried do have their drawbacks—either clumping all docs in the class docstring (making per-member lookups hard) or repeating member names when setting __doc__ manually. Here's a cleaner, more maintainable solution that avoids both issues:
Step 1: Create a Reusable DocEnum Base Class
We'll extend Python's built-in Enum to support attaching docstrings directly to members during definition, without repeating names:
from enum import Enum class DocEnum(Enum): def __new__(cls, value, doc=None): # Create the enum instance obj = object.__new__(cls) # Set the underlying value (so .value returns the correct type, not a tuple) obj._value_ = value return obj def __init__(self, value, doc=None): # Assign the docstring directly to the member self.__doc__ = doc
Step 2: Define Your Enum with Docstrings
Now use DocEnum as your base class, and define each member as a tuple of (value, docstring):
class Color(DocEnum): RED = (1, "The color red") GREEN = (2, "The color green") BLUE = (3, "The color blue. These docstrings are more useful in the real example")
How This Works
- The Enum metaclass automatically unpacks the tuple values into arguments for
__new__and__init__. __new__sets the actual value of the enum member (soColor.RED.valuereturns1, not the tuple).__init__assigns the docstring to the member's__doc__attribute, which IPython recognizes perfectly.
Why This Is Better Than Your Original Approaches
- No name repetition: Each member is defined exactly once, with its value and docstring paired together.
- Per-member doc access: In IPython, running
help(Color.RED)will show the specific docstring for that member, not the entire class docstring. - Clean, maintainable structure: Docs are right next to the values they describe, making it easier to update or modify later.
Testing in IPython
If you fire up IPython and run:
help(Color.RED)
You'll see output like:
Help on Color in module __main__ object: RED = <Color.RED: 1> The color red
Perfect—exactly what you want!
内容的提问来源于stack exchange,提问作者Eric
相关产品推荐
相关产品推荐

