You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为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 (so Color.RED.value returns 1, 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 09:34:49