Does python always need to compile ENTIRE program before it can start to run it???

Peter Hansen peter at engcorp.com
Mon Nov 3 21:29:41 CET 2003


Francis Avila wrote:
> 
> "Ellinghaus, Lance" <lance.ellinghaus at eds.com> wrote in message
> news:mailman.385.1067888457.702.python-list at python.org...
> > Python always compiles your scripts to bytecode before it can be executed.
> > It cannot and does not do partial compilation and execution.
> >
> > But this is not the whole story. Python does not always have to do the
> > compilation phase. When Python loads a module (.py file) from an 'import'
> > statement, it will see if there is an already compiled version in the same
> > directory and named the same except for the '.pyc' or '.pyo' extension. If
> > it finds this file AND it is newer than the corresponding source code
> (.py)
> > then it will load the saved compilation and then run it. If the file is
> not
> > found or it is older than the source, then Python will compile the source,
> > attempt to save the compiled version, and then it will execute it.
> 
> Actually, I Python will only use a compiled version if the source and the
> compiled version have *exactly* the same date.  (This is a much better
> approach anyway--suppose you want to run an older version?)
> 
> I only say this because I read "if it is newer" more often than not.
> 
> This reference has the rundown on the relationship between py-pyc-pyo files:
> http://www.python.org/doc/current/tut/node8.html#SECTION00812000000000000000

And in fact that note does point out that it's not the date *of* the .pyc
file which matters, but the date that is quietly stored inside it, which
comes from the timestamp of the .py file.

Easy proof: import a file, "touch" the .pyc file to have a different date,
import the file again (in a new Python interactive session).  The .pyc is
not recompiled, but is used as-is.

-Peter




More information about the Python-list mailing list