python - 从Python中编译的字符串返回函数

标签 python

我正在尝试从字符串创建一个函数并从另一个 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. If globals and locals 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 and locals are the same dictionary. If exec gets two separate objects as globals and locals, 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/

相关文章:

python - 当元素有多个类时,BeautifulSoup SoupStrainer 不起作用?

python - 根据多个条件向 Python Pandas DataFrame 添加新列

python - 将新列添加到 pandas DataFrame 时的 NaN 值

python - Django:用户只能编辑或删除与其帐户绑定(bind)的对象

python - 具有多个匹配项的 opencv python MatchTemplate 函数

python - numpy数组区域统计

python - 如何从 "python setup.py test"运行 unittest discover ?

python - 从 Python 写入机器人框架控制台

python - Numpy 随机选择,仅沿一个轴替换

python - Pygame 矩形不会更新