如何将Python函数转为字符串及反向转换为可调用函数?
Python函数与字符串互转的实现方案
刚好处理过类似的需求,下面分两部分给你讲清楚怎么实现:
1. 将函数转为字符串(模拟JS的function.toString())
Python里要获取函数的源代码字符串,最实用的工具是inspect模块的getsource()方法,它能直接提取函数的原始代码文本。针对你给出的示例函数:
import inspect def someFunction(hey): return hey + hey + hey # 获取函数的源代码字符串 func_string = inspect.getsource(someFunction) print(func_string) # 输出就是你要的:def someFunction(hey): return hey + hey + hey
如果函数里包含注释,想要自动清除掉的话,可以用ast模块解析代码的抽象语法树,过滤掉注释节点后再生成干净的代码:
import ast import inspect def strip_comments(source_code): # 解析代码为AST tree = ast.parse(source_code) # 遍历节点,移除所有注释类的表达式节点 for node in ast.walk(tree): if isinstance(node, ast.FunctionDef): node.body = [n for n in node.body if not (isinstance(n, ast.Expr) and isinstance(n.value, ast.Constant) and isinstance(n.value.value, str))] # 将处理后的AST转回代码字符串 return ast.unparse(tree) # 先获取原始代码,再去除注释 raw_code = inspect.getsource(someFunction) clean_code = strip_comments(raw_code) print(clean_code)
2. 将函数字符串转回可调用的函数
要把字符串形式的函数定义变成能直接调用的函数对象,用exec()是最直观的方案:
# 假设我们已经有了函数字符串 func_str = "def someFunction(hey): return hey + hey + hey" # 执行这段代码,函数会被加载到当前命名空间 exec(func_str) # 现在直接调用就行 print(someFunction("test")) # 输出: testtesttest
如果担心污染全局命名空间,可以创建一个局部字典来执行代码,避免影响其他变量:
func_str = "def someFunction(hey): return hey + hey + hey" local_scope = {} # 在局部作用域里执行代码 exec(func_str, globals(), local_scope) # 从局部字典里取出函数 my_callable_func = local_scope["someFunction"] print(my_callable_func("hello")) # 输出: hellohellohello
另外还有更底层的compile()+types.FunctionType方案,但exec()足够应对大部分场景,没必要搞复杂。
内容的提问来源于stack exchange,提问作者Daniel Müller
相关产品推荐
相关产品推荐

