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

如何为Python项目文档添加自定义标签过滤器/分类器

基于Sphinx的实现方案

1. 给函数添加标准格式的标签

采用Sphinx Napoleon风格的标签定义,在docstring中加入:tags: tag1:

# ModuleB.py
def e():
    """
    函数e的功能描述

    :tags: tag1
    """
    pass

# ModuleB.py
def f():
    """
    函数f的功能描述

    :tags: tag1
    """
    pass

2. 配置Sphinx收集标签信息

在项目的conf.py中添加事件钩子,提取函数的标签并存储:

def collect_tagged_objects(app, what, name, obj, options, lines):
    tags = []
    # 从docstring中解析标签
    for line in lines:
        stripped_line = line.strip()
        if stripped_line.startswith(":tags:"):
            tags = [t.strip() for t in stripped_line.split(":tags:")[1].split(",")]
            break
    if not tags:
        return
    
    # 初始化存储容器
    if not hasattr(app.env, 'tagged_objects'):
        app.env.tagged_objects = {}
    
    # 按标签分类存储函数信息
    for tag in tags:
        if tag not in app.env.tagged_objects:
            app.env.tagged_objects[tag] = []
        app.env.tagged_objects[tag].append({
            "module": obj.__module__,
            "func_name": name,
            "docstring": "\n".join(lines)
        })

def setup(app):
    # 绑定autodoc文档处理事件
    app.connect('autodoc-process-docstring', collect_tagged_objects)

3. 创建标签分类页面

新建tag1_functions.rst文件,使用Jinja2模板渲染收集到的tag1函数:

{% set tag1_funcs = env.tagged_objects.get('tag1', []) %}

带有tag1标签的函数
==================

{% for func in tag1_funcs %}
{{ func.module }}.{{ func.func_name }}
--------------------------------------

**所属模块**: {{ func.module }}

{{ func.docstring }}
{% endfor %}

最后在index.rst中通过.. include:: tag1_functions.rst将该页面加入文档结构,执行sphinx-build即可生成包含tag1分区的文档。


内容的提问来源于stack exchange,提问作者codebrew

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 03:57:32