Why are main runnable Python scripts not compiled to pyc files like modules? -


i understand when import module, file compiled .pyc file make faster? why main file not compiled .pyc? slow things down? better keep main file small possible then, or not matter?

when module loaded, py file "byte compiled" pyc files. time stamp recorded in pyc files. this done not make run faster load faster. hence, makes sense "byte compile" modules when load them.

[edit : include notes, references]

from pep 3147 on "byte code compilation":

cpython compiles source code "byte code", , performance reasons, caches byte code on file system whenever source file has changes. makes loading of python modules faster because compilation phase can bypassed. when source file foo.py, cpython caches byte code in foo.pyc file right next source.

how byte code compiled files tracked respect python version , "py" file changes:

it inserts magic number in compiled byte code ".pyc" files. changes whenever python changes byte code format, in major releases.
ensures pyc files built previous versions of vm won't cause problems. timestamp used make sure pyc file match py file used create it. when either magic number or timestamp not match, py file recompiled , new pyc file written.

"pyc" files not compatible across python major releases. when python finds pyc file non-matching magic number, falls slower process of recompiling source.

thats reason, if distribute ".pyc" files compiled same platform not work more, if python version changes.

in nutshell

if there byte compiled file ".pyc" , it's timestamp indicates recent loaded other wise python fallback on slower approach of loading ".py" files. execution performance of ".py" file not affected loading of ".pyc" files faster ".py" files.

consider executing a.py imports b.py

typical total performance = loading time (a.py) + execution time (a.py) +                              loading time (b.py) + execution time (b.py)   since loading time (b.pyc)  <  loading time (b.py)  should see better performance using byte compiled "pyc" files.  

that said, if have large script file x.py, modularizing , moving contents other modules results in taking advantage of lower load time byte code compiled file.

another inference modules tend more stable script or main file. hence not byte compiled @ all.

references


Comments

Popular posts from this blog

ASP.NET/SQL find the element ID and update database -

jquery - appear modal windows bottom -

c++ - Compiling static TagLib 1.6.3 libraries for Windows -