EOL EOL - 1 year ago 89
Python Question

How to programmatically set a global (module) variable?

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
that contains variables that can be accessed as
, etc., where all values are obtained through parsing a file (hence the need to do the assignments in a "programmatic" way).

Now, the
solution above would work. But I am a little bit uneasy with it, because I'm afraid that
is not the cleanest way to achieve the goal of setting module globals.

Answer Source

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
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download