Module executed twice when imported!
Simon Forman
rogue_pedro at yahoo.com
Wed Jun 28 18:37:10 EDT 2006
Michael Abbott wrote:
> 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.
I don't get it either but there may be a clue in the docs for the
execfile() function
(http://docs.python.org/lib/built-in-funcs.html#l2h-24)
"It is different from the import statement in that it does not use the
module administration --"
I don't know why the globals dict you're passing in would change the
behavior though. Hopefully someone else can enlighten us both.
Peace,
~Simon
More information about the Python-list
mailing list