Friday 12 July 2013

Compiling Python code

I know that compiling python code to bytecode speeds loading of code, however I never really thought about how to do this until now.
There appears to be multiple ways to do this according to the documentation.

The first method runs the code and generate an .pyc file.
In the python interpreter just import your .py file, e.g.
>>> import myfile.py


The next method I have come across is to use the py_compile module, e.g
import py_compile

py_compile.compile("myfile.py")



The next method is to use the compiler package, note this is marked as deprecated since version 2.6 and has been removed from version 3, e.g.
import compiler

compiler.compileFile(myfile.py")

With multiple files this could become time consuming, therefore there is another module compileall, which will compile all files in a directory, e.g.
import compileall 

compileall.compile_dir("mylib")

In the above example it will not recompile exisiting .pyc files if the corresponding .py timestamp has not been updated (timestamp is stored in .pyc file). To force compilation add argument force=1 when calling compile_dir().
See documentation for more useful options.