cytochrome
cytochrome

Reputation: 549

importing large numbers of variables into namespace

I am refactoring a large scientific program. The main code for the application consists of tens of equations using hundreds of parameters. Because this calculation code has been tested extensively, I don't want to change it.

Some of the parameters may be logically lumped together in sets, e.g., there may be sets of parameters corresponding to a given instrument. Simulations are to be run by swapping in and out different sets of parameters.

I would like to maintain the parameters in a separate file so that they may be changed easily.

My question is this: How do I 'import' the parameters into the calculation module namespace in a way that will allow me to specify which sets are used?

Right now, I am using what seems to be a hack. In the parameters module, I hold values in dictionaries. For example,

----- start params_module -----
instrument1 = dict(param1=1.0, param2=2.0, ...)
instrument2 = dict(param1=3.0, param2=4.0, ...)
instrument3 = dict(param1=5.0, param2=6.0, ...)
misc_params = dict(param10 = 10, param11=20, ...)
...
----- end params_module -----

I then import the dictionary of interest in the calculation_module namespace and add it into the globals dictionary:

--- start calculation_module -----
from params_module import instrument1, misc_params
globals().update(instrument1) 
globals().update(misc_params)
...
many equations that make use of param1, param2, etc.
...
--- end calculation_module -----

Is there a more Pythonic way to do this?

Thank you.

-cytochrome

Upvotes: 2

Views: 94

Answers (1)

HYRY
HYRY

Reputation: 97261

You method is ok, but if you want to change the parameters in calculation_module, you need to change the calculation_module.py code. I will use execfile instead.

from params_module import instrument1, misc_params
env = {}
env.update(instrument1) 
env.update(misc_params)

execfile("calculation_module.py", env)

#get your result form env

Upvotes: 3

Related Questions