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

如何提取Python函数return语句中的返回变量名称

解决方案:解析Python函数/类返回变量名的实现方法

你要的返回变量名属于静态代码结构信息,inspect库仅能获取运行时元数据、无法识别源码层面的返回变量标识,可通过Python内置的ast(抽象语法树)模块实现需求,支持多返回值、条件分支返回、return位置不固定等场景。

核心实现步骤

  • 用inspect.getsource()获取目标函数/类方法的源码文本
  • 用ast.parse()将源码解析为抽象语法树
  • 遍历语法树节点,筛选所有Return类型节点,提取节点对应返回值的变量/表达式标识

完整可运行示例代码

import ast
import inspect
from typing import List, Set

def get_return_varnames(func) -> Set[tuple]:
    # 获取函数源码
    source_code = inspect.getsource(func)
    # 解析为AST
    tree = ast.parse(source_code)
    
    return_varnames = set()
    
    # 自定义AST节点遍历器
    class ReturnVisitor(ast.NodeVisitor):
        def visit_Return(self, node):
            if node.value is None:
                # 无返回值的return
                return_varnames.add(())
                return
            # 处理多返回值(元组返回)
            if isinstance(node.value, ast.Tuple):
                current_return = []
                for elt in node.value.elts:
                    # 如果是直接变量,取变量名;如果是表达式取表达式的源码表示
                    if isinstance(elt, ast.Name):
                        current_return.append(elt.id)
                    else:
                        current_return.append(ast.unparse(elt))
                return_varnames.add(tuple(current_return))
            else:
                # 单返回值
                if isinstance(node.value, ast.Name):
                    return_varnames.add((node.value.id,))
                else:
                    return_varnames.add((ast.unparse(node.value),))
            # 继续遍历子节点
            self.generic_visit(node)
    
    ReturnVisitor().visit(tree)
    return return_varnames

# 测试用例1:基础单返回函数
def sample_function(parameter_1, parameter_2):
    # some logic
    return_value = 1
    return return_value

# 测试用例2:多分支多返回值函数
def test_func(a, b):
    if a > b:
        res1 = a + b
        res2 = a - b
        return res1, res2
    elif a == b:
        return "equal"
    else:
        return a * 2, b * 2, a + b

# 调用测试
print(get_return_varnames(sample_function)) # 输出 {('return_value',)}
print(get_return_varnames(test_func)) # 输出 {('res1', 'res2'), ('equal',), ('a * 2', 'b * 2', 'a + b')}

注意事项

  • 若目标函数是C实现的内置函数、或者无法获取源码的动态生成函数,本方法不适用
  • 对于返回值为复合表达式的场景,代码中默认返回表达式的源码文本,可根据你的模板生成需求调整提取逻辑
  • 类的实例方法、静态方法、类方法都可以直接传入该函数获取返回变量名

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 01:45:03