import ( how to put a symbol into caller's namespace )

Steven D. Majewski (sdm7g@elvis.med.virginia.edu)
Thu, 24 Mar 1994 15:38:53 -0500

Putting this thread together with the one on tracebacks
inspired me with the solution of how to enter a new name
into the caller's namespace.

caller() causes an error with the statement: "1 + ''" .
It then follows the traceback frame to get it's caller's
caller's frame.

ImportModule calls the earlier version of importmodule,
calls caller() to get it's caller's frame, and enters
module `modname` into that frame's f_globals global
dictionary.

This allows:
ImportModule( pathname, 'XXX' )
instead of the redundant:
XXX = importmodule( pathname, 'XXX' )

- Steve Majewski (804-982-0831) <sdm7g@Virginia.EDU>
- UVA Department of Molecular Physiology and Biological Physics

#------- Yet Another Version of newmod.py -----------
import sys

def newmodule( modname ):
import null_module
sys.modules[modname] = sys.modules['null_module']
sys.modules[modname].__name__ = modname
del sys.modules['null_module']
del null_module
return sys.modules[modname]

def importmodule( filename, modname ):
module = newmodule( modname )
execfile( filename, module.__dict__, module.__dict__ )
return module

def caller():
try:
1 + '' # make an error happen
except: # and return the caller's caller's frame
return sys.exc_traceback.tb_frame.f_back.f_back

def ImportModule( filename, modname ):
newmodule = importmodule( filename, modname )
frame = caller() # get the caller's frame
frame.f_globals[modname] = newmodule # and enter name in dict