如何量化统计Python项目各代码结构的docstring占比
Python项目docstring占比量化统计方案
完全可以实现,不需要从零造复杂轮子,有两类成熟路径可选:
直接使用现成专用工具
- 推荐用
interrogate,这是专门做Python docstring覆盖率统计的工具,支持覆盖模块、类、函数、异步函数、类方法等所有需要统计的代码结构,可输出精确的占比数值,还支持自定义排除规则、设置覆盖率门禁、对接CI流程。
安装命令:pip install interrogate
递归统计当前项目目录的基础命令:interrogate -v .
执行后会直接输出待检查结构总数、已写docstring的结构数、最终覆盖率百分比,同时会列出缺失docstring的具体代码位置。 - 如果你已经在项目里用了pylint、pydocstyle这类linter,也可以开启这类工具的docstring缺失检查规则,导出检查结果后做简单计数就能算出占比,缺点是需要自己写少量脚本处理输出,灵活度高但便捷性不如专用工具。
零依赖自定义脚本实现
如果不想额外安装第三方包,用Python标准库自带的ast模块就能快速实现统计逻辑,核心是通过抽象语法树遍历所有需要统计的代码节点,判断节点是否绑定有效的docstring,最后计算占比即可,极简实现参考:
import ast from pathlib import Path def calc_single_file(file_path): with open(file_path, 'r', encoding='utf-8') as f: tree = ast.parse(f.read()) total = 1 with_doc = 1 if ast.get_docstring(tree) else 0 for node in ast.walk(tree): if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef)): total += 1 with_doc += 1 if ast.get_docstring(node) else 0 return total, with_doc if __name__ == "__main__": total_cnt = 0 doc_cnt = 0 for py_file in Path(".").rglob("*.py"): file_str = str(py_file) # 按需调整要排除的目录 if any(skip in file_str for skip in [".venv", "__pycache__", "test_"]): continue t, d = calc_single_file(file_str) total_cnt += t doc_cnt += d coverage = round(doc_cnt / total_cnt * 100, 2) if total_cnt else 0 print(f"docstring覆盖率:{coverage}%(总统计节点{total_cnt}个,含docstring节点{doc_cnt}个)")
脚本可以根据自身需求灵活调整规则,比如是否统计私有方法、是否排除特定目录/文件、是否区分内部方法和公开接口的统计逻辑等。
内容的提问来源于stack exchange,提问作者Henrique Branco
相关产品推荐
相关产品推荐

