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

如何通过Python代码从外部文件提取枚举类的文档字符串?

提取枚举类文档字符串的实现方案

这里提供两种可靠的实现方式,可根据场景选择:

方法一:AST语法树解析(安全无执行风险)

此方法直接分析源码的语法结构,不会执行目标文件,适合处理未知或不可信的枚举文件。

import ast

def get_documentation(path_to_file):
    with open(path_to_file, 'r', encoding='utf-8') as f:
        source_code = f.read()
    
    # 解析源码为抽象语法树
    tree = ast.parse(source_code)
    
    # 遍历AST节点,定位继承自IntEnum的类
    for node in ast.walk(tree):
        if isinstance(node, ast.ClassDef):
            # 检查类的基类是否包含IntEnum
            for base in node.bases:
                if isinstance(base, ast.Name) and base.id == 'IntEnum':
                    # 返回去除首尾空白的文档字符串
                    return node.docstring.strip() if node.docstring else None
    return None

方法二:动态导入模块(简单直接)

如果目标枚举文件是可信的,可通过动态导入模块的方式直接访问枚举类的__doc__属性。

import importlib.util
import os

def get_documentation(path_to_file):
    # 提取文件名作为模块名
    module_name = os.path.splitext(os.path.basename(path_to_file))[0]
    
    # 创建并加载模块
    spec = importlib.util.spec_from_file_location(module_name, path_to_file)
    module = importlib.util.module_from_spec(spec)
    spec.loader.exec_module(module)
    
    # 遍历模块成员,找到IntEnum子类
    for name, obj in vars(module).items():
        try:
            # IntEnum同时继承int和Enum,通过__members__属性识别
            if issubclass(obj, int) and hasattr(obj, '__members__'):
                return obj.__doc__.strip() if obj.__doc__ else None
        except TypeError:
            # 跳过非类对象
            continue
    return None

测试代码

使用你提供的测试逻辑即可验证:

path_to_file = "./Enumeration1.py"
doc = get_documentation(path_to_file)
print(doc)  # 输出 "Some documentation."

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 09:15:33