如何为Python常量编写文档以适配Intellisense与Sphinx?
方案1:靠VSCode Pylance的内嵌提示搞定
打开VSCode设置,搜索python.analysis.inlayHints.defaultValues,将其设为true。开启后,代码里会在函数参数旁直接显示width: int = 416的提示,悬停查看函数帮助时,也会同时展示参数说明和具体默认值。
保留docstring里的The default is constants.WIDTH.即可,这样Sphinx生成的文档能明确标注默认值的常量来源,VSCode用户又能通过内嵌提示看到具体数值,两头需求都能满足。
优点:无需修改代码或文档,零维护成本;同时适配IDE提示和文档生成场景
缺点:仅在VSCode+Pylance环境下生效,换其他编辑器可能看不到内嵌提示
方案2:让Sphinx自动把常量名换成具体值
先把docstring里的默认值说明改成占位符形式:
Args: width (int): Width of the network from which the images will be processed. Must be a multiple of 32. The default is {constants.WIDTH}.
然后在Sphinx的conf.py中添加一段自定义逻辑,让它生成文档时自动替换这些占位符:
import constants def autodoc_process_docstring(app, what, name, obj, options, lines): for i, line in enumerate(lines): if "{constants." in line: lines[i] = line.format(constants=constants) def setup(app): app.connect('autodoc-process-docstring', autodoc_process_docstring)
这样Sphinx生成的文档里会显示The default is 416.,而VSCode悬停时虽然看到的是{constants.WIDTH},但可以直接点击该常量跳转到constants.py查看具体值。
优点:Sphinx文档显示具体值,无需手动同步;docstring保留常量引用,明确默认值来源
缺点:需要编写少量Sphinx扩展代码;VSCode中无法直接看到具体值,需跳转查看
方案3:用pre-commit钩子自动同步docstring里的常量值
如果希望docstring直接显示具体值又不想手动维护,可以用pre-commit钩子自动更新:
- 安装
pre-commit,在项目根目录创建.pre-commit-config.yaml文件 - 编写脚本
update_constants_in_docs.py,用于扫描代码中的docstring,替换常量引用为具体值:import ast import constants def update_docstrings(file_path): with open(file_path, 'r', encoding='utf-8') as f: content = f.read() tree = ast.parse(content) for node in ast.walk(tree): if isinstance(node, ast.FunctionDef) and ast.get_docstring(node): docstring = ast.get_docstring(node) for name, value in vars(constants).items(): if name.isupper(): docstring = docstring.replace(f"constants.{name}", str(value)) node.body[0].value.s = docstring with open(file_path, 'w', encoding='utf-8') as f: f.write(ast.unparse(tree)) if __name__ == "__main__": import sys for file in sys.argv[1:]: update_docstrings(file) - 在
.pre-commit-config.yaml中添加该钩子:repos: - repo: local hooks: - id: update-constants-in-docs name: Update constants in docstrings entry: python update_constants_in_docs.py language: system files: \.py$
每次提交代码前,pre-commit会自动把docstring里的constants.WIDTH替换为416,无需手动操作。
优点:docstring直接显示具体值,VSCode和Sphinx都能直接展示;无需手动同步常量值与文档
缺点:需要配置pre-commit环境;提交后的代码仅显示具体数值,看不到常量引用
方案4:手动写双份说明(简单直接但需维护)
直接在docstring中同时标注常量名和具体值:
Args: width (int): Width of the network from which the images will be processed. Must be a multiple of 32. The default is constants.WIDTH (416).
这种方式无需额外配置,VSCode用户能直接看到具体值,Sphinx文档也能明确默认值来源。唯一的问题是修改常量时需要同步更新docstring里的数值,容易遗漏。
优点:零配置,简单易懂;同时满足两种场景需求
缺点:修改常量时需手动维护docstring,存在遗漏风险
内容的提问来源于stack exchange,提问作者vlopezb0

