How to pass parameter when importing a module?

Bo Peng bpeng at rice.edu
Sun Mar 20 11:18:14 EST 2005


Dear list,

What I would like to do is something like:

In myModule.py ( a wrapper module for different versions of the module),

   if lib == 'standard':
     from myModule_std import *
   elsif lib == 'optimized'
     from myModule_op import *

but I do not know how to pass variable lib to myModule.py to achieve the 
following effect:

   >>> lib = 'standard'
   >>> from myModule import *     # actually import myModule_std

 From what I have read, from .... does not take any parameter. Maybe I 
should use environmental variables?

   >>> os.putenv('lib', 'standard')
   >>> from myModule import *

   myModule.py
   -------------
   import os
   lib = os.getenv('lib')
   ...


or use a separate module?

   param.py
   ---------

   para = {}
   def setParam(key, val):
     para[key] = val

   main session
   ------------
   >>> import param
   >>> param.setParam('lib','standard')
   >>> from myModule import *

   in myModule.py
   --------------
   from param import para
   try:
     lib = para['lib']
   except:
     lib = 'standard'
   ...

Is there an established approach for this problem?

Many thanks in davance.
Bo

===============================================================================
FULL STORY:

I have several modules all (SWIG) wrapped from the same C++ source code 
but with different compiling flags. For example,

   myModule_std  (standard module)
   myModule_op   (optimized, without error checking)
   ...

These modules are put directly under /.../site-packages . To load a 
module, I use, for example

   from myModule_op import *

This works fine until I need to write some helper functions for 
myModule_?? in another module myHelper.py since I do not know which 
myModule is being used

   from myModule?? import A,B

I find one solution

   # find out which module is being used
   import sys
   if 'myModule_op' in sys.modules.keys():
     from myModule_op import A,B
   else:
     from myModule_std import A,B

but not completely satisfied. Therefore, I am writing a 'wrapper' module 
myModule that can load one of the myModule_?? modules according to user 
supplied info.




More information about the Python-list mailing list