How to programmatically set a global (module) variable?
Question:
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).
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.
Answers:
You can set globals in the dictionary returned by globals():
definitions = {'a': 1, 'b': 2, 'c': 123.4}
for name, value in definitions.items():
globals()[name] = value
You’re right, exec
is usually a bad idea and it certainly isn’t needed in this case.
Ned’s answer is fine. Another possible way to do it if you’re a module is to import yourself:
fundamentalconstants.py:
import fundamentalconstants
fundamentalconstants.life_meaning= 42
for line in open('constants.dat'):
name, _, value= line.partition(':')
setattr(fundamentalconstants, name, value)
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)
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).
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.
You can set globals in the dictionary returned by globals():
definitions = {'a': 1, 'b': 2, 'c': 123.4}
for name, value in definitions.items():
globals()[name] = value
You’re right, exec
is usually a bad idea and it certainly isn’t needed in this case.
Ned’s answer is fine. Another possible way to do it if you’re a module is to import yourself:
fundamentalconstants.py:
import fundamentalconstants
fundamentalconstants.life_meaning= 42
for line in open('constants.dat'):
name, _, value= line.partition(':')
setattr(fundamentalconstants, name, value)
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)