views:

110

answers:

4

I cannot seem to find a good simple explanation of what python does differently when running with the -O or optimize flag.

+6  A: 

assert statements are completely eliminated, as are statement blocks of the form if __debug__: ... (so you can put your debug code in such statements blocks and just run with -O to avoid that debug code).

With -OO, in addition, docstrings are also eliminated.

Alex Martelli
+6  A: 

From the docs:

When the Python interpreter is invoked with the -O flag, optimized code is generated and stored in .pyo files. The optimizer currently doesn’t help much; it only removes assert statements. When -O is used, all bytecode is optimized; .pyc files are ignored and .py files are compiled to optimized bytecode.

Passing two -O flags to the Python interpreter (-OO) will cause the bytecode compiler to perform optimizations that could in some rare cases result in malfunctioning programs. Currently only __doc__ strings are removed from the bytecode, resulting in more compact .pyo files. Since some programs may rely on having these available, you should only use this option if you know what you’re doing.

A program doesn’t run any faster when it is read from a .pyc or .pyo file than when it is read from a .py file; the only thing that’s faster about .pyc or .pyo files is the speed with which they are loaded.

So in other words, almost nothing.

ire_and_curses
+2  A: 

From What does the -O flag do?

It somewhat depends on the Python version. To find out precisely what it does, search the source code for Py_OptimizeFlag. In 2.5, it

  • causes the interpreter to load .pyo files, not .pyc files (in .zip files, just makes .pyo preferred over .pyc)
  • causes __debug__ to have a value of 0
  • ignores assert statements in source code
  • treats __debug__ statically as being 0
  • causes the byte code generator to save .pyo files, not .pyc
joaquin
Correct your formatting, __debug__ -> `__debug__`
gorsky
+1  A: 

As answered in python optimization mode:

python -O does the following currently:

  • completely ignores asserts
  • sets the special builtin name __debug__ to False (which by default is True)

and when called as python -OO

  • removes docstrings from the code

I don't know why everyone forgets to mention the __debug__ issue; perhaps it is because I'm the only one using it :) An if __debug__ construct creates no bytecode at all when running under -O, and I find that very useful.

ΤΖΩΤΖΙΟΥ
Note that this answer is an exact copy of my answer in [that](http://stackoverflow.com/questions/2055557/python-optimized-mode) question from Jan 13, 2010; in his answer to that question, Alex Martelli didn't mention the `if __debug__` construct, and that is why my answer here seems to be out-of-place (my “why everyone forgets to mention”).
ΤΖΩΤΖΙΟΥ