What does Python optimization (-O or PYTHONOPTIMIZE) do?

PythonOptimizationPython 3.x

Python Problem Overview


The docs only say that Python interpreter performs "basic optimizations", without going into any detail. Obviously, it's implementation dependent, but is there any way to get a feel for what type of things could be optimized, and how much run-time savings it could generate?

Is there any downside to using -O?

The only thing I know is that -O disables assert, but presumably one shouldn't use assert for things that could still go wrong in production.

Python Solutions


Solution 1 - Python

In Python 2.7, -O has the following effect:

In addition -OO has the following effect:

To verify the effect for a different release of CPython, grep the source code for Py_OptimizeFlag.

Link to official documentation: https://docs.python.org/2.7/tutorial/modules.html#compiled-python-files

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionmaxView Question on Stackoverflow
Solution 1 - PythonMartin v. LöwisView Answer on Stackoverflow