[Python-Dev] __file__

Nick Coghlan ncoghlan at gmail.com
Sun Feb 28 06:11:54 CET 2010


Glenn Linderman wrote:
> Thanks for the explanation.  Brett mentioned something like runpy vs
> import using different techniques.  Which is OK, I guess, but if the
> command line/runpy can do it, the importer could do it.  Just a matter
> of desire and coding.  Whether it is worth pursuing further depends on
> people's perceptions of "kookiness" vs. functional and performance
> considerations.

As I said previously, don't underestimate how different __main__ is from
everything else. The most obvious difference is that the code for
__main__ is executed without holding the import lock, but there are
other important differences as well (such as the module object being
created directly by the interpreter startup sequence and hence a lot of
the import machinery being bypassed). Even the -m switch doesn't really
follow the normal import paths (it just finds the code object for the
named module and then runs it directly instead of importing it).

Direct execution starts with a filename (or a module name when using -m)
then works out how to execute it as __main__. Importing starts with a
module name, tries to find a matching filename and create the
corresponding module. The different starting points and the different
end goals affect the assumptions that are made while the interpreter
figures out what it needs to do.

The behaviour of runpy is different from import precisely because it
aims to mimic execution of __main__ rather than a normal import. If
there weren't quite so many semantic differences between direct
execution and normal import, the module would have been a lot easier to
write :)

Cheers,
Nick.

-- 
Nick Coghlan   |   ncoghlan at gmail.com   |   Brisbane, Australia
---------------------------------------------------------------


More information about the Python-Dev mailing list