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

如何通过独立脚本自动维护Python函数Docstring并更新参数选项?

自动维护Python函数Docstring的实现方案

核心需求

实现可重复的Docstring维护流程:当函数依赖的Enum参数选项变更时,自动更新函数的Docstring,替代之前直接修改文件文本的冗余基础方案。具体场景为:one.py中定义的do_something函数使用two.py中DoSomethingParams Enum类作为参数,通过three.py自动同步Enum的参数选项到该函数的Docstring中。

three.py代码实现(AST方案)

使用Python的ast模块解析和修改代码,AST能精准定位函数节点和Docstring,避免文本操作的不稳定问题:

import ast
import os
from two import DoSomethingParams

def update_docstring(target_file: str, func_name: str, enum_cls):
    # 读取目标文件内容
    with open(target_file, 'r', encoding='utf-8') as f:
        content = f.read()
    
    # 解析为AST
    tree = ast.parse(content)
    
    # 遍历AST节点,找到目标函数
    for node in ast.walk(tree):
        if isinstance(node, ast.FunctionDef) and node.name == func_name:
            # 生成Enum参数选项的文本
            enum_options = ', '.join([f"`{member.name}`" for member in enum_cls])
            # 构造新的Docstring内容(示例结构,可根据实际需求调整)
            new_docstring = f"""
            执行指定操作的函数。
            
            参数:
                param: 操作类型,可选值为 {enum_options}
            """
            # 更新函数的Docstring
            node.body[0] = ast.Expr(value=ast.Constant(value=new_docstring.strip()))
            break
    
    # 将修改后的AST转换回代码文本
    updated_content = ast.unparse(tree)
    
    # 写回目标文件
    with open(target_file, 'w', encoding='utf-8') as f:
        f.write(updated_content)

# 执行更新
if __name__ == "__main__":
    update_docstring("one.py", "do_something", DoSomethingParams)

代码说明

  • 利用ast模块解析one.py的代码结构,精准定位do_something函数节点
  • 动态获取DoSomethingParams的所有成员,生成参数选项文本
  • 替换函数的Docstring节点后,通过ast.unparse将AST还原为代码并写回文件
  • 该方案无需手动定位Docstring的文本位置,适配不同格式的函数定义

其他可行实现方案

1. 装饰器方案

定义一个装饰器,在函数运行时动态生成或更新Docstring,适合不需要修改源文件,仅在运行时展示最新Docstring的场景:

from functools import wraps
from two import DoSomethingParams

def sync_enum_doc(enum_cls, param_name: str):
    def decorator(func):
        @wraps(func)
        def wrapper(*args, **kwargs):
            # 动态生成Docstring
            enum_options = ', '.join([f"`{member.name}`" for member in enum_cls])
            func.__doc__ = f"""
            执行指定操作的函数。
            
            参数:
                {param_name}: 操作类型,可选值为 {enum_options}
            """.strip()
            return func(*args, **kwargs)
        return wrapper
    return decorator

# 在one.py中使用装饰器
# @sync_enum_doc(DoSomethingParams, "param")
# def do_something(param):
#     pass

2. 代码生成工具方案

使用自定义脚本或模板工具,基于Enum定义自动生成或更新函数的Docstring。适合项目有统一代码生成流程的场景:

  • 编写包含函数结构和占位符Docstring的模板文件
  • 脚本读取Enum成员,替换模板中的占位符,生成更新后的函数代码
  • 将生成的代码覆盖或合并到目标文件中

3. Linter/Formatter插件方案

自定义flake8或black的插件,在代码检查/格式化时自动同步Enum参数到Docstring:

  • 插件解析代码中的函数和依赖的Enum
  • 检查Docstring中的参数选项是否与Enum一致
  • 自动修复不一致的Docstring内容,配合IDE实时触发或CI流水线执行

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.26 13:03:20