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

如何通过Python AST获取函数调用的第一个输入参数?

问题原因分析
  • 你编写的CallVisitor类在主逻辑中完全没有被调用,当前的遍历逻辑只输出Attribute节点的attr属性,因此只能拿到assertEqual、fromkeys两个属性名,没有定位到self.assertEqual对应的Call节点;同时你遍历得到的node大多是Attribute、Name类型,根本没有args属性,尝试访问node.args[0]自然得不到预期结果。
  • 即使你拿到了正确的参数节点,直接打印节点对象只会输出节点的类型描述,不会输出对应的原始代码字符串,需要把AST节点反序列化为源码文本。
修复后的实现代码

Python 3.9+ 版本(内置支持AST反序列化)

import ast

if __name__ == '__main__':
    source = """self.assertEqual(dictlike.fromkeys('a'), {'a':None})"""
    root = ast.parse(source)
    # 遍历定位到self.assertEqual对应的Call节点
    for node in ast.walk(root):
        if isinstance(node, ast.Call) and isinstance(node.func, ast.Attribute) and node.func.attr == 'assertEqual':
            # 将第一个参数节点反序列化为源码字符串
            first_arg_code = ast.unparse(node.args[0])
            print(first_arg_code)

运行输出:dictlike.fromkeys('a')

低于Python 3.9版本

需要先安装第三方库astor:

pip install astor

修改代码如下:

import ast
import astor

if __name__ == '__main__':
    source = """self.assertEqual(dictlike.fromkeys('a'), {'a':None})"""
    root = ast.parse(source)
    for node in ast.walk(root):
        if isinstance(node, ast.Call) and isinstance(node.func, ast.Attribute) and node.func.attr == 'assertEqual':
            first_arg_code = astor.to_source(node.args[0]).strip()
            print(first_arg_code)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 03:36:04