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

已知Tuple/List等typing类型标注如何实例化对应结构对象?

Python mock C库返回值类型解析与实例生成问题

我目前正在开发用于mock某C语言库的Python代码,借助pybind可以获取库函数及对应的docstring,本次任务目标是实现这类函数的返回值mock。

现状

目前已经可以通过正则成功读取任意函数的返回值标注,接下来需要解析返回值类型、提取类型内部的泛型参数,将其初始化为预设值或填充对应实例。示例实现逻辑如下:

docstring = parse(getattr(MyClass, the_method_I_want_to_mock).__doc__)

# 正则匹配从 -> 开始到输出提示末尾的返回值类型部分
method_type_search = re.search(r"(?<=-> ).+(?=)", docstring.short_description)

# 匹配成功后执行eval得到类型对象
evaluated_method = eval(method_type_search.group(0))

执行到这一步时,evaluated_method的取值类似typing.Tuple[int, int]。

核心实现目标

  • 提取返回值的外层类型
  • 提取类型内部包含的泛型参数(例如处理tuple/list时提取其内部元素类型)
  • 结合前两步结果实例化对应结构:例如typing.Tuple[int, int]需生成(0, 0),typing.List[float, user_class]需生成[0.0, user_class()]

现有代码与存在的问题

当前已编写的实现代码如下:

# eval_method 为前述形如`typing.Tuple[int, int]`的类型对象
def test_evaluate_types(eval_method):
    # 类型到默认预设值的映射字典:基础类型直接返回对应值,自定义类则返回实例
    # 例如遇到user_class类型时需要实例化,int类型对应0
    evaluate_dict: dict = { 
        int: 0,
        List[int]: [0, 1, 2]
    }
    out = []
    # 判断是否为带泛型的复合类型,还是单一基础类型
    try:
        eval_method_type = eval_method._name
    except AttributeError:
        # 单一基础类型直接返回映射字典里的预设值
        return evaluate_dict[eval_method]

    # 提取泛型参数,例如Tuple[int,int]会得到[<class 'int'>, <class 'int'>]
    eval_method_output = eval_method.__args__
    # 遍历泛型参数,逐个生成对应实例
    for idx, output in enumerate(eval_method_output):
        out.append(evaluate_dict[output])

    # 原本想把生成的元素列表转成对应外层类型的实例,但是这里逻辑失效,卡在这里了
    return eval(eval_method_type + f"({out})") 

目前最后一步将解析得到的元素列表转换为对应外层类型实例的逻辑无法正常运行,现有实现冗余度较高,需要一套更简便的方案,支持将任意类型(包含用户自定义类型)按规则转换为对应的预设实例。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.26 16:57:23