Python中如何将带中间变量的函数转为可eval执行的表达式字符串?
可行实现方案
推荐直接用Python内置的ast模块做语法解析+变量内联,纯标准库无第三方依赖,生成的表达式字符串无冗余,存储效率完全符合要求,具体实现如下:
实现代码
import ast import inspect import math def function_to_expr(func): # 获取函数的源码 src = inspect.getsource(func) # 解析为AST语法树 tree = ast.parse(src) # 存储中间变量到对应表达式的映射 var_map = {} # 遍历函数体节点 func_body = tree.body[0].body for node in func_body: # 处理赋值语句,记录中间变量对应的表达式 if isinstance(node, ast.Assign): var_name = node.targets[0].id var_map[var_name] = ast.unparse(node.value) # 处理return语句,替换所有中间变量为实际表达式 elif isinstance(node, ast.Return): return_expr = ast.unparse(node.value) # 循环替换支持中间变量嵌套引用 updated = True while updated: updated = False for var, expr in var_map.items(): new_expr = return_expr.replace(var, f"({expr})") if new_expr != return_expr: return_expr = new_expr updated = True return return_expr # 测试用你提供的原函数 import math def f(x): a = x - math.log(x) b = x + math.log(x) return a / x + b / math.log(x) # 生成表达式字符串 expr = function_to_expr(f) print(expr) # 输出:(x - math.log(x)) / x + (x + math.log(x)) / math.log(x) # 验证运行结果 func = lambda x: eval(expr) print(func(3)) # 输出:4.364513583657809
注意事项
- 该实现默认函数为纯数学计算的顺序赋值结构,无分支、循环等复杂逻辑,完全适配你描述的使用场景
- 支持中间变量嵌套引用,比如
b = a + 2这类写法也能正常展开 - 如果你使用Python3.9以下版本,可安装轻量第三方库
astunparse,将代码中的ast.unparse替换为astunparse.unparse即可正常运行 - 生成的表达式字符串没有任何冗余内容,存储体积和手动写的完全一致
内容的提问来源于stack exchange,提问作者Shaun Han
相关产品推荐
相关产品推荐

