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.
The best way to share global variables across modules across a single program is to create a config module. Just import the config module in all modules of your application; the module then becomes available as a global name.
The global Keyword Normally, when you create a variable inside a function, that variable is local, and can only be used inside that function. To create a global variable inside a function, you can use the global keyword.
Creating global parameters To create a global parameter, go to the Global parameters tab in the Manage section. Select New to open the creation side-nav. In the side-nav, enter a name, select a data type, and specify the value of your parameter.
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)
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With