Import without executing module

rdmurray at rdmurray at
Tue Feb 10 11:13:47 EST 2009

Lie Ryan <lie.1296 at> wrote:
> On Tue, 03 Feb 2009 20:08:34 -0800, Stephen Hansen wrote:
> > There is no need to try to make sure something is
> > executed/compiled only once in Python like you may want to do in C.
> > Every module is only ever compiled once: if you import it ten times in
> > ten different places only the first will compile and execute the code,
> > the rest of the calls will return that original module again.
> <nitpick>
> If you import a module, it will be recompiled only if the module changes 
> from the precompiled .pyc/.pyo. OTOH, if you run a module, it will be 
> recompiled every time even if there is no change.
> </nitpick>

As long as we are nitpicking, and trying to clarify things for a new
Python user....let me give it a try.  By doing this I get to find out
if I really understand it as well as I think I do :)

If a file is run as a script ('python', or shebang magic on
unix or the equivalent on other OSes), then the code is compiled/executed
each time that is done.  If a module is imported (or something is imported
from a module), then the _first time_ during a given run of the python
interpreter that such an import is done, the timestamp of the .py file
(if it exists) is compared to the timestamp of the .pyc/.pyo file, and
if the .py is newer, the .py file is compiled to byte code, the resulting
byte code is written to the .pyc (or .pyo), and the byte code is executed.
If the .py file is older, then the saved byte code is loaded and executed.
It is the execution of the byte code that creates the module's namespace
(a collection of names pointing to objects).  This namespace is registered
in sys.modules under the module's name.  During the remainder of that
run of the python interpreter, any import statement that draws from
that module simply loads a pointer to the module's namespace (or to
objects referenced by the module's namespace if it is a 'import from')
into the local namespace.


More information about the Python-list mailing list