Python bytecode compatibility between interpreter versions

Delaney, Timothy C (Timothy) tdelaney at avaya.com
Sun Mar 21 22:03:42 EST 2004


> From: Jon Perez
> 
> Is it really the case that it isn't even recommended to 
> distribute one's
> application as .pyc files?

No - this is not the case. It is perfectly fine to distribute using .pyc files, and in fact this is what py2exe does. However, it is then required that the correct version of Python be used.

> > Java does something similar behind the scenes with HotSpot.
> > It compiles things to native code, and keeps profiling information.
> > They are not written out to disk and hence are not persistent
> > between executions, but if they were the usage would be analogous
> > to .pyc files.
> 
> In Java, profiling info may not be written out to disk, but the
> bytecodes certainly are (they are what is in the class files).  Which
> is roughly equivalent to what happens with .pyc files, correct?   .pyc
> files don't contain profiling info, nor was I ever aware that 
> the Python
> VM even does run-time behaviour profiling... (Pysco may, though)

This is not what is being described. There is no requirement for .pyc (or .pyo) files to be created, but you can rely on a particular released version of python being able to use .pyc files generated by the same minor version of CPython. However, you cannot rely on the .pyc file *actually* being used - for example, if there is a .py file with the same name and different timestamp in the directory, the .pyc file will be ignore and (unless read-only) will be overwritten by a new .pyc file.
> 
> In practice though, there is really just one implementation of Python
> (with the standard libraries... excluding Jython) which works 
> using the
> same bytecode mechanism on _all_ platforms, so as far as I can tell,
> it would be quite feasible to distribute applications in .pyc form.

This is correct, with the caveat that you can only rely on it working with a specific version.

Note that Jython does not actually create .class files (unless you run jythonc) - it actually creates the java bytecode in memory and uses a custom classloader. CPython does a similar thing - when it reads a .py file, it creates the bytecode in memory. If possible the bytecode is written to a .pyc file for later reuse, but it doesn't have to, and will work just fine if it can't.

Tim Delaney




More information about the Python-list mailing list