我正在尝试从字符串创建一个函数并从另一个 Python 函数返回它。下面的例子
def compile_functions() -> t.Callable:
code = """def f():\n\treturn 1"""
compiled = compile(code, "<string>", "exec")
exec(code)
return f
但是这会产生NameError: name 'f' is not Defined
。我错过了什么?
最佳答案
exec()
在与定义 compile_functions()
方法的范围不同的范围内运行您的代码。根据 exec()
的docs :
If only
globals
is provided, it must be a dictionary, which will be used for both the global and the local namespace. Ifglobals
andlocals
are given, they are used for the global and local namespace, respectively. If provided,locals
can be any mapping object. Remember that at module level,globals
andlocals
are the same dictionary. If exec gets two separate objects asglobals
andlocals
, the code will be executed as if it were embedded in a class definition.
因此,作为解决方案,您需要将空 {}
填充到 exec()
的 globals
参数中。更新了代码,现在将返回预期的 1
:
def compile_functions() -> t.Callable:
code = """def f():\n\treturn 1"""
compiled = compile(code, "<string>", "exec")
namespace = {}
exec(compiled, namespace)
return namespace['f']
关于python - 从Python中编译的字符串返回函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/76084731/