I would like to define globals in a "programmatic" way. Something similar to what I want to do would be:
我想以“程序化”的方式定义全局变量。类似于我想做的事情将是:
definitions = {'a': 1, 'b': 2, 'c': 123.4}
for definition in definitions.items():
exec("%s = %r" % definition) # a = 1, etc.
Specifically, I want to create a module fundamentalconstants
that contains variables that can be accessed as fundamentalconstants.electron_mass
, etc., where all values are obtained through parsing a file (hence the need to do the assignments in a "programmatic" way).
具体来说,我想创建一个模块基本常量,其中包含可以作为fundamentalconstants.electron_mass等访问的变量,其中所有值都是通过解析文件获得的(因此需要以“编程”方式进行分配)。
Now, the exec
solution above would work. But I am a little bit uneasy with it, because I'm afraid that exec
is not the cleanest way to achieve the goal of setting module globals.
现在,上面的exec解决方案可行。但我对它有点不安,因为我担心exec不是实现设置模块全局变量目标的最干净的方法。
3 个解决方案
#1
38
You can set globals in the dictionary returned by globals():
您可以在globals()返回的字典中设置全局变量:
definitions = {'a': 1, 'b': 2, 'c': 123.4}
for name, value in definitions.items():
globals()[name] = value
#2
49
Here is a better way to do it:
这是一个更好的方法:
import sys
definitions = {'a': 1, 'b': 2, 'c': 123.4}
module = sys.modules[__name__]
for name, value in definitions.iteritems():
setattr(module, name, value)
#3
4
You're right, exec
is usually a bad idea and it certainly isn't needed in this case.
你是对的,exec通常是一个坏主意,在这种情况下肯定不需要。
Ned's answer is fine. Another possible way to do it if you're a module is to import yourself:
奈德的答案很好。如果你是一个模块,另一种可行的方法是自己导入:
fundamentalconstants.py:
fundamentalconstants.py:
import fundamentalconstants
fundamentalconstants.life_meaning= 42
for line in open('constants.dat'):
name, _, value= line.partition(':')
setattr(fundamentalconstants, name, value)
#1
38
You can set globals in the dictionary returned by globals():
您可以在globals()返回的字典中设置全局变量:
definitions = {'a': 1, 'b': 2, 'c': 123.4}
for name, value in definitions.items():
globals()[name] = value
#2
49
Here is a better way to do it:
这是一个更好的方法:
import sys
definitions = {'a': 1, 'b': 2, 'c': 123.4}
module = sys.modules[__name__]
for name, value in definitions.iteritems():
setattr(module, name, value)
#3
4
You're right, exec
is usually a bad idea and it certainly isn't needed in this case.
你是对的,exec通常是一个坏主意,在这种情况下肯定不需要。
Ned's answer is fine. Another possible way to do it if you're a module is to import yourself:
奈德的答案很好。如果你是一个模块,另一种可行的方法是自己导入:
fundamentalconstants.py:
fundamentalconstants.py:
import fundamentalconstants
fundamentalconstants.life_meaning= 42
for line in open('constants.dat'):
name, _, value= line.partition(':')
setattr(fundamentalconstants, name, value)