Accessing global namespace from module

Gabriel Genellina gagsl-py2 at yahoo.com.ar
Mon Jun 11 23:49:14 EDT 2007


En Mon, 11 Jun 2007 22:19:15 -0300, Reuben D. Budiardja  
<techlist at pathfinder.phys.utk.edu> escribió:

> One last question. Do I have to do this for ever script I write, or can  
> I put
> this into separate file and "include" it somehow ?
> I am going to have several mainscripts.py, and all is going to import  
> myModule
> that will need access to this plots subroutine. It'll be great if I can  
> put
> this trick on a single file that is included by the main scripts, to  
> avoid
> violating DRY principle.

According to your description on how things work, you will need the  
globals() from mainscript.py; try this:

--- mainscript.py ---
import plot_setup
plot_setup.setup(globals())
... rest of script, perhaps importing myModule.py ...

--- plot_setup.py ---
import sys
 from types import ModuleType as module

def setup(namespace):
     plotModule = module('plot')
     for key,value in namespace.items():
         if key[:2] != '__':
             setattr(plotModule, key, value)
     sys.modules['plot'] = plotModule

--- myModule.py ---
import plot

def do_work():
     plot.DrawPlot(...)
     ...

(Having to type two lines at the top of your main scripts doesn't look so  
bad...)

-- 
Gabriel Genellina




More information about the Python-list mailing list