Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 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.

like image 841
Eric O Lebigot Avatar asked Sep 15 '09 21:09

Eric O Lebigot


People also ask

How do I create a global variable in Python with modules?

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.

How do you declare a variable as a global variable?

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.

How do you set global parameters?

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.


2 Answers

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) 
like image 167
Nadia Alramli Avatar answered Oct 10 '22 09:10

Nadia Alramli


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 
like image 32
Ned Batchelder Avatar answered Oct 10 '22 07:10

Ned Batchelder