who imported me?

Thomas Malik malik.thomas at lbbw.de
Fri Jan 19 09:34:40 EST 2001


sragsdale at my-deja.com wrote:
> 
> (Hopefully) easy question: I'm writing a module that uses values in
> variables from the script that imported it.
> 
> How can I tell which script is importing me?
> 
you can't, since the code in module's global level is executed only once
( during the initial import) and nothing is passed into an imported
module by default.

> Is there some easier way to get the parent module's variable values?
> 
use execfile instead, here you can pass any dictionary ( including
globals() ) as global scope for the execution of the code inside the
file (by saying 'scope' i mean the set of variable bindings, don't know
a better word for that). So you may, inside the file, access variables
from the current (calling) module. If you need some module to come out
of the whole process, you can import an empty dummy module, copy all
global variables from the current module into the dummy module, and pass
dummy.__dict__ as global scope to execfile, like this:

testmod.py:
# 'almost-module' to be 'imported' as dummy, needs to know importing
module's scope
print 'testmod: i was called by', __name__
print 'testmod: just_for_fun =', just_for_fun
print 'testmod: calling test():\n', test()
 
# set some variable
new_var =
1                                                                     

dummy.py:
# everything inside testmod.py shall show up inside this module, as if
the code in testmod.py
# had been defined here.
just_for_fun = 0
print 'dummy: __name__ =', __name__

main.py:
 
import dummy
 
# function to be visible inside 'testmod'
def test():
  print 'test(), __name__ =', __name__
  print 'test: dummy.just_for_fun =', dummy.just_for_fun
  return 'test result'
 
# copy main.py's scope into dummy's scope
dummy.__dict__.update(globals())
# exec testmod.py and put all assignments/defs into dummy's scope
execfile("testmod.py", dummy.__dict__)
 
# actually set in testmod
print 'dummy.new_var =',
dummy.new_var                                            
print 'dummy.__name__ =', dummy.__name__
# Note that __name__ will be wrongly set in dummy from main.py's
__name__ 
# (you may decide to reset it after the execfile)
dummy.__name__ = 'dummy'
print dummy.test() # is main.py's test, actually, __name__ will still
print as '__main__' in test() call
# has gone into dummy, not here: NameError
print 'just_for_fun =', just_for_fun



Thomas



More information about the Python-list mailing list