gpt4 book ai didi

python - 将Python源代码加载到函数对象中

转载 作者:行者123 更新时间:2023-12-01 02:26:27 25 4
gpt4 key购买 nike

我需要创建一个类似单元测试的框架,用于单函数 python 作业的轻量级自动评分。我很乐意做如下的事情:

test = """
def foo(x):
return x * x
"""

compiled_module = magic_compile(test)
result = compiled_module.foo(3)
assert result == 9

有这样的magic_compile函数吗?到目前为止我拥有的最好的是

exec(test)
result = getattr(sys.modules[__name__], 'foo')(3)

但这似乎很危险且不稳定。这不会在生产中运行,所以我不太关心沙箱和安全性。只是想确保我没有缺少更好的解决方案。

最佳答案

在 Python 3.x 中:

module = {}
exec(test, module)
assert module['foo'](3) == 9

module 不是真正的 Python 模块,它只是一个命名空间,用于保存代码的全局变量,以避免污染模块的命名空间。

关于python - 将Python源代码加载到函数对象中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47339192/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com