在Python中调用函数时,它看到的全局变量始终是其定义所在模块的全局变量。(如果不正确,则该函数可能无法正常工作-实际上可能 需要
一些全局值,并且您不一定要知道它们是什么。)指定带有
exec或
eval()仅影响
exec‘d或
eval()‘d看到的代码的全局变量的全局字典。
如果要让函数看到其他全局变量,则确实必须在传递给
exec或的字符串中包含函数定义
eval()。当您这样做时,函数的“模块”就是从其编译的字符串,带有其自己的全局变量(即,您提供的全局变量)。
您可以通过使用与要调用的代码对象相同的代码对象创建一个新函数来解决此问题
func_globals,但是该函数指向您的globals
dict却具有不同的属性,但这是相当先进的黑客技术,可能不值得。不过,这是您的处理方式:
# create a sandbox globals dictsandbox = {}# create a new version of test() that uses the sandbox for its globalsnewtest = type(test)(test.func_pre, sandbox, test.func_name, test.func_defaults, test.func_closure)# add the sandboxed version of test() to the sandboxsandbox["test"] = newtest


