Module executed twice when imported!

Georg Brandl g.brandl-nospam at gmx.net
Fri Jun 30 23:19:35 CEST 2006


Michael Abbott wrote:
> In article <05epg.2385$No6.49436 at news.tufts.edu>,
>  John Salerno <johnjsal at NOSPAMgmail.com> wrote:
> 
>> > (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 --"
>> 
>> Just after the above statement, it also says:
>> 
>> "it reads the file unconditionally and does not create a new module."
>> 
>> so perhaps that means that it isn't really being imported the second 
>> time, just that the contents are being executed?
> 
> Interesting thought.
> 
> I'm not convinced, though: firstly, I read that statement as describing 
> what happens to the file named in the execfile() statement;  and 
> secondly, the problem *only* happens if the global dictionary passed to 
> execfile() has a '__name__' and if the value of that key is sufficiently 
> close to the name of the file being passed to execfile().
> 
> I found that passing __name__='whatever' resulted in normal import 
> behaviour, and so does __name__='subtest', but curiously enough passing 
> __name__='subtest.' results in the double import.

That's because __name__ is normally set to the module's name in the package
hierarchy. When you set it to "some1.some2", Python thinks it's
in a subpackage and when it does "import imptest" Python searches for
the module "some1.imptest", not for "imptest", and finds it in the
current directory (which it assumes to be the package directory).

You can verify this by inspecting sys.modules after the execfile() call.

So it's not a bug, but expected behavior.

Georg



More information about the Python-list mailing list