Module executed twice when imported!

Bruno Desthuilliers bdesth.quelquechose at free.quelquepart.fr
Thu Jun 29 04:07:15 CEST 2006


Michael Abbott a écrit :
> 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).

During module evaluation, __name__ is usually set to the name of the 
module *object*, not the name of the *file*. I suspect that it has 
something to do with your observation.



More information about the Python-list mailing list