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.

Answer from tzot on Stack Overflow
🌐
Python.org
discuss.python.org › ideas
Does anyone use `-O` or `-OO` or `PYTHONOPTIMIZE=1` in their deployments? - Ideas - Discussions on Python.org
November 1, 2023 - I expect the answer to the question in the subject for most is “No”… In that case, you are not who I’m interested in hearing from. It’d be good to hear from CPython users who actually use -O, -OO, or PYTHONOPTIMIZE=1 to have Python elide assert statements (performance?) or (-OO) omit ...
Discussions

What is the use of Python's basic optimizations mode? (python -O) - Stack Overflow
Python has a flag -O that you can execute the interpreter with. The option will generate "optimized" bytecode (written to .pyo files), and given twice, it will discard docstrings. From Python's man... More on stackoverflow.com
🌐 stackoverflow.com
optimization - What are the implications of running python with the optimize flag? - Stack Overflow
What does Python do differently when running with the -O (optimize) flag? More on stackoverflow.com
🌐 stackoverflow.com
May 14, 2010
Add support for optimized mode (`-O`) in `uv run`
The standard CPython interpreter has a handful of flags that can be set when executing a Python program, most of which are not directly supported by uv run. Do the uv maintainers have any plans to support additional flags, specifically the following optimization-related flags? More on github.com
🌐 github.com
6
February 16, 2025
Usage of assert statements in optimized mode
I've noticed that Lark uses assert statements in some places outside of tests. Just by doing git grep assert in the lark directory we can see a big list of these. Assert statements are ignored when Python is running in optimized mode. Op... More on github.com
🌐 github.com
2
July 13, 2018
🌐
Python.org
discuss.python.org › ideas
Stop ignoring asserts when running in optimized mode - Ideas - Discussions on Python.org
January 13, 2022 - Following a Twitter discussion, I was interested to get some feedback around the idea of making a PEP to have assert statements always execute, independently of Python’s optimize mode. I will be taking some time in the near future to lay out what I think can be the pros and cons, but if some ...
🌐
Real Python
realpython.com › lessons › pythonoptimize-variable
Setting the PYTHONOPTIMIZE Environment Variable (Video) – Real Python
03:03 You can use any integer number to set PYTHONOPTIMIZE, but Python only implements two levels of optimization. Using a number greater than 2 has no real effect on your compiled bytecode. 03:15 Setting PYTHONOPTIMIZE to 0 will cause the interpreter to return to normal mode.
Published   April 25, 2023
🌐
Python
wiki.python.org › moin › PythonSpeed › PerformanceTips
PythonSpeed/PerformanceTips - Python Wiki
It's often useful to place them inside functions to restrict their visibility and/or reduce initial startup time. Although Python's interpreter is optimized to not import the same module multiple times, repeatedly executing an import statement can seriously affect performance in some circumstances.
🌐
GitHub
github.com › python › typing › discussions › 1598
Type hints and optimized mode · python/typing · Discussion #1598
While reviewing a PR I came across a somewhat interesting case - the validity of the return type depending on whether Python is running in optimized mode (starting Python with -O or PYTHONOPTIMIZE ...
Author   python
Find elsewhere
🌐
GitHub
github.com › astral-sh › uv › issues › 11547
Add support for optimized mode (`-O`) in `uv run` · Issue #11547 · astral-sh/uv
February 16, 2025 - The standard CPython interpreter has a handful of flags that can be set when executing a Python program, most of which are not directly supported by uv run. Do the uv maintainers have any plans to support additional flags, specifically the following optimization-related flags?
Author   gusutabopb
🌐
GitHub
github.com › lark-parser › lark › issues › 185
Usage of assert statements in optimized mode · Issue #185 · lark-parser/lark
July 13, 2018 - Assert statements are ignored when Python is running in optimized mode. Optimize mode is used in some projects when Python is deployed and/or distributed.
Author   petermlm
Top answer
1 of 1
1

Using compile

I've come up with a solution using the built-in function compile, as follows.

Contents of the file main.py:

with open('test.py') as f:
    source_code = f.read()
compiled = compile(
    source_code,
    filename='test.py', mode='exec', optimize=2)
exec(compiled)

Contents of the file test.py:

if __debug__:
    print('Debug ON')
else:
    print('Debug OFF')

The output from running python main.py is:

Debug OFF

Possible values for the parameter optimize:

  • -1: use same optimization level as the Python interpreter that is running the function compile
  • 0: no optimization, and __debug__ == true
  • 1: like -O, i.e., removes assert statements, and __debug__ == false
  • 2: like -OO, i.e., removes also docstrings.

Don't know if it's the best option, just sharing if can be useful fo others.

Using subprocess.run

The subprocess-based approach is still more concise, and can be made portable by using sys.executable:

import subprocess
import sys

if not sys.executable:
    raise RuntimeError(sys.executable)
proc = subprocess.run(
    [sys.executable, '-OO', 'test.py'],
    capture_output=True, text=True)
if proc.returncode != 0:
    raise RuntimeError(proc.returncode)

The above code calls the function subprocess.run.

The check for the value of the variable sys.executable is motivated by the documentation of CPython:

If Python is unable to retrieve the real path to its executable, sys.executable will be an empty string or None.

The check is implemented with a raise statement, instead of an assert statement, in order to check also in cases that the above Python code is itself run with optimization requested from Python, e.g., by using python -O or python -OO or the environment variable PYTHONOPTIMIZE.

When optimization is requested, assert statements are removed.

Using raise statements also enables raising an exception other than AssertionError, in this case RuntimeError.

For running Python code that is within a function inside the same source file (i.e., inside main.py, not inside test.py), the function inspect.getsource can be used, together with the option -c of python.

By the way better answers are welcome!

🌐
Medium
medium.com › @bremer_21076 › how-to-optimize-python-code-the-right-way-a-beginners-guide-to-profiling-34c4c0f07dc4
How to optimize Python code the right way — a beginners guide to profiling | by Klaus Bremer | Medium
November 28, 2023 - But for the slowest length method (a property) it is different. From this method the functions math.pow and math.sqrt are called adding the corresponding tottimes to the cumtime of length. In modern Python interpreters the math.pow function is applied to the buildin ** operator and the length method can be simplified to:
🌐
Real Python
realpython.com › python-assert-statement
Python's assert: Debug and Test Your Code Like a Pro – Real Python
January 12, 2025 - This is the default or normal Python mode, in which all your assertions are enabled because __debug__ is True. On the other hand, if __debug__ is False, then the code under the outer if statement doesn’t run, meaning that your assertions will be disabled. In this case, Python is running in optimized mode.
🌐
SciPy
docs.scipy.org › doc › scipy › tutorial › optimize.html
Optimization (scipy.optimize) — SciPy v1.17.0 Manual
Scientific Python Forum · Search Ctrl+K · The scipy.optimize package provides several commonly used optimization algorithms. A detailed listing is available: scipy.optimize (can also be found by help(scipy.optimize)). The minimize function provides a common interface to unconstrained and constrained minimization algorithms for multivariate scalar functions in scipy.optimize.
🌐
YouTube
youtube.com › live › 6kMGphTUOUk
python's optimization mode is mostly useless (intermediate) anthony explains #523 - YouTube
today I talk about python's `-O` and `-OO` and why they're all but useless- python is compiled? https://youtu.be/FPJdre3mbD4- asserts: https://youtu.be/v1Mtw...
Published   February 10, 2023
🌐
Python
python-list.python.narkive.com › kAu3Sb4C › initializing-python-in-optimized-mode-from-c
Initializing Python in Optimized mode from C++
Post by JT When embedding Python in C++, is there anyway to initialize the interpreter so that it runs in optimized mode, equivalent to specifying the -O flag when running the interpreter from the command line? here's one way to do it: putenv("PYTHONOPTIMIZE=yes"); ...
🌐
Python.org
discuss.python.org › ideas
Stop ignoring asserts when running in optimized mode - #35 by stoneleaf - Ideas - Discussions on Python.org
January 17, 2022 - One option I have not seen that would be better than the status quo: turn assert off by default make -O be a noop add a command line switch, say --debug or --assert that enables assert Presto chango, problem solved! People stop using assert inappropriately.