forcing future re-import from with an imported module

_wolf wolfgang.lipp at gmail.com
Wed Dec 10 02:27:10 CET 2008


following problem: i have a module importer_1 that first imports
importer_2, then importee. importer_2 also imports importee. as we all
know, follow-up imports are dealt out from the cache by python’s
import mechanism, meaning the importee file gets only cached once. i
can force module-level code in importee to be re-executed e.g. by
deleting importee from sys.modules. but in this case, code of shich
below, that does not work: if you delete importee from sys.modules
*from within importee*, you get a nasty "ImportError: Loaded module
importee not found in sys.modules" instead. but, the same line `import
sys; del sys.modules[ 'importee' ]` does what it says on the tin.

how can i say, approximately, "re-import the present module when it is
imported the next time, don’t use the cache" in a simple way? i do not
want to "reload" the module, that doesn’t help.

greets

_wolf



#------------------------------------------
# importer_1.py
#------------------------------------------

print 'this is importer 1'
import importer_2
# import sys; del sys.modules[ 'importee' ]
import importee
print 'importer 1 finished'

#------------------------------------------
# importer_2.py
#------------------------------------------

print 'this is importer 2'
import importee
print 'importer 2 finished'

#------------------------------------------
# importee.py
#------------------------------------------

print 'this is importee'
import sys; del sys.modules[ 'importee' ]
print 'importee finished'

#------------------------------------------
# Output
#------------------------------------------
this is importer 1
this is importer 2
this is importee
importee finished
Traceback (most recent call last):
  File "C:\temp\active_imports\importer_1.py", line 2, in <module>
    import importer_2
  File "C:\temp\active_imports\importer_2.py", line 2, in <module>
    import importee
ImportError: Loaded module importee not found in sys.modules



More information about the Python-list mailing list