Module executed twice when imported!

Michael Abbott michael at araneidae.co.uk.invalid
Wed Jun 28 23:52:15 CEST 2006


It seems to be an invariant of Python (insofar as Python has invariants) 
that a module is executed at most once in a Python session.  I have a 
rather bizzare example that breaks this invariant: can anyone enlighten 
me as to what is going on?

--- test.py ---
import imptest
execfile('subtest.py', dict(__name__ = 'subtest.py'))
--- imptest.py ---
print 'Imptest imported'
--- subtest.py ---
import imptest
---

   $ python test.py
   Imptest imported
   Imptest imported
   $

Hmm.  If the value __name__ is omitted from the dictionary, or if its 
value doesn't match at least 'subtest.' then the message is printed only 
once (for example, passing dict(__name__='subtest') produces one 
"imported" message).

This happens with both python 2.4 and 2.3.  I don't get it.



More information about the Python-list mailing list