从外部模块执行全局变量
exec a global variable from an extern module
我有一个外部模块,我想在其中将 "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()
表示 "the globals dict of this module"。因此,您选择的编码方式 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
更快更清洁。
globals()
总是 return 调用它的模块的 __dict__
。这真的是唯一合理的选择……考虑一下:
# qux.py
import foo
foo.bar()
# foo.py
import baz
def bar():
return baz.exec_stuff()
# baz.py
def exec_stuff():
exec 'A = 1' in globals()
全局应该设置在qux.py
还是foo.py
还是baz.py
?这样看,baz
是 最 明显的选择,也是 python 使用的选择。
现在我们要问的问题是 为什么首先要使用 exec?通常,return 是调用者所需的值更好的主意。然后他们就可以用它做他们想做的事了:
def fn_in_extern_module():
return 42
然后:
import extern
A = extern.fn_in_extern_module()
我有一个外部模块,我想在其中将 "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()
表示 "the globals dict of this module"。因此,您选择的编码方式 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
更快更清洁。
globals()
总是 return 调用它的模块的 __dict__
。这真的是唯一合理的选择……考虑一下:
# qux.py
import foo
foo.bar()
# foo.py
import baz
def bar():
return baz.exec_stuff()
# baz.py
def exec_stuff():
exec 'A = 1' in globals()
全局应该设置在qux.py
还是foo.py
还是baz.py
?这样看,baz
是 最 明显的选择,也是 python 使用的选择。
现在我们要问的问题是 为什么首先要使用 exec?通常,return 是调用者所需的值更好的主意。然后他们就可以用它做他们想做的事了:
def fn_in_extern_module():
return 42
然后:
import extern
A = extern.fn_in_extern_module()