Home | Posts RSS | Comments RSS | Login

How to compile Python source file with or without optimization

Sunday, September 21, 2008

py_compile and compileall module provides functions to generate a byte-code file from a source file. You can not, however, enable or disable byte code optimization at runtime.

The byte code optimization depends the built-in variable __debug__ in the current interpreter, and assignments to __debug__ are illegal. Python 2.2 (or later) is strict about that.

% python
Python 2.5.1 (r251:54863, Apr 15 2008, 22:57:26) 
[GCC 4.0.1 (Apple Inc. build 5465)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> __debug__
True
>>> __debug__ = False
  File "<stdin>", line 1
SyntaxError: can not assign to __debug__

So you can't enable/disable optimization flag without running another interpreter (using '-O' switch).

Example: Using os.spawnv to run and compile files with or without optimization

0 comments to How to compile Python source file with or without optimization: