我有一个 extern 模块,我想将“exec”表达式设置为全局(因为我需要将字符串作为变量名称传递)
所以,我有一个类似的功能
def fct_in_extern_module():
exec 'A = 42' in globals()
return None
在我的主脚本中我有
import extern_module
extern_module.fct_in_extern_module()
那么,为什么我有
NameError: name 'A' is not defined
如果我这样做(在主脚本中)
def fct_in_main():
exec 'B = 42' in globals()
fct_in_main()
>>> B
42
知道如何将字符串“A”设置为外部模块中的变量名吗?
谢谢!
最佳答案
globals()
表示“此模块的全局字典”。因此,您选择的 extern_module.py
编码方式将不会影响任何其他模块的全局字典。
一种修复方法:将其定义为:
def fct_in_extern_module(where):
exec 'A = 42' in where
并将其命名为:
extern_module.fct_in_extern_module(globals())
当然,像往常一样,exec
并不是解决问题的最佳方法。更好:
def fct_in_extern_module(where):
where['A'] = 42
更快、更干净。
关于python - 从外部模块执行全局变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31887664/