Another use for the -O flag is that the value of the __debug__ builtin variable is set to False.

So, basically, your code can have a lot of "debugging" paths like:

if __debug__:
     # output all your favourite debugging information
     # and then more

which, when running under -O, won't even be included as bytecode in the .pyo file; a poor man's C-ish #ifdef.

Remember that docstrings are being dropped only when the flag is -OO.

Answer from tzot on Stack Overflow
🌐
Real Python
realpython.com › python-assert-statement
Python's assert: Debug and Test Your Code Like a Pro – Real Python
January 12, 2025 - So, make sure that you’re not running Python in optimized mode. You can check the current value of your PYTHOPTIMIZE environment variable by running the following command: ... If PYTHONOPTIMIZE is set, then this command’s output will display its current value. A remarkable feature to note is that pytest integrates nicely with the assert statement. The library can display error reports with detailed information about the failing assertions and why they’re failing. As an example, check out the the lines starting with the E letter in the above output.
Discussions

pytest, assert keyword and optimized mode
I find using assert keyword and pytest/pytest-django much more Pythonic and elegant for writing tests, that’s why I’ve used factory-boy, pytest-django, Faker and django-test-plus packages to write tests, for the first time. However, when I shared my public repo (https://github.com/Ksen... More on forum.djangoproject.com
🌐 forum.djangoproject.com
1
0
January 13, 2022
Is common best practice in python to use assert for business logic?
Don’t use assert outside of tests. the Python runtime has a flag -O (for optimize) that ignores assert statements. If you use asserts for business logic, and someone decides to run your code in production and thinks it’s a good idea to optimize the bytecode, your code breaks More on reddit.com
🌐 r/Python
138
205
July 14, 2024
Stop ignoring asserts when running in optimized mode - Ideas - Discussions on Python.org
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 ... More on discuss.python.org
🌐 discuss.python.org
6
January 13, 2022
Feature: Python assert should be consider harmful
In python the assert statements are ignored when running in optimize mode. This can lead to code misbehaving in production because the wrong check is in place. An old thread on the topic but still relevant: We would love to have a Sonar rule that would flag assert statements so that we can ... More on community.sonarsource.com
🌐 community.sonarsource.com
0
0
February 11, 2021
🌐
GitHub
github.com › lark-parser › lark › issues › 185
Usage of assert statements in optimized mode · Issue #185 · lark-parser/lark
July 13, 2018 - I did a quick experiment, and running the following like of code fails in both normal and optimized mode: lark.Lark(grammar='start: "my_token"', parser='not_a_parser') But the yielded exception is different. Normal mode is: Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/home/my_user/opensource/lark/lark/lark.py", line 108, in __init__ self.options = LarkOptions(options) File "/home/my_user/opensource/lark/lark/lark.py", line 68, in __init__ assert self.parser in ('earley', 'lalr', 'cyk', None) AssertionError
Author   petermlm
🌐
Dot Net Perls
dotnetperls.com › assert-python
Python - assert, O Option - Dot Net Perls
Python stops and signals the assert call. With this statement, we can ensure a program's state is correct. And by providing the "O" option on the command line, we can optimize out all assert calls. Tip Assert() only has an effect when __debug__ is true. We can disable __debug__ with a command-line parameter. This example ...
🌐
Python documentation
docs.python.org › 3 › reference › simple_stmts.html
7. Simple statements — Python 3.14.4 documentation
These equivalences assume that __debug__ and AssertionError refer to the built-in variables with those names. In the current implementation, the built-in variable __debug__ is True under normal circumstances, False when optimization is requested (command line option -O).
🌐
Python
docs.python.org › 2.0 › ref › assert.html
6.2 Assert statements
May 24, 2014 - These equivalences assume that __debug__ and AssertionError refer to the built-in variables with those names. In the current implementation, the built-in variable __debug__ is 1 under normal circumstances, 0 when optimization is requested (command line option -O).
Find elsewhere
🌐
Python Morsels
pythonmorsels.com › assert-statement
Python's assert statement - Python Morsels
October 9, 2023 - Now, you may sometimes hear Python developers discourage the use of assert because assert statements can be disabled in Python. If you run Python with the optimize flag, which is -O, Python will set the value of the __debug__ variable to False (it defaults to True):
🌐
Python Reference
python-reference.readthedocs.io › en › latest › docs › statements › assert.html
assert — Python Reference (The Right Way) 0.1 documentation
These equivalences assume that __debug__ and AssertionError refer to the built-in variables with those names. In the current implementation, the built-in variable __debug__ is True under normal circumstances, False when optimization is requested (command line option -O).
🌐
Snyk
snyk.io › blog › the-dangers-of-assert-in-python
The dangers of assert in Python | Snyk
August 18, 2022 - Keeping "`time=" as the t value, execute the simple interest program in optimized mode using the following command: ... 1PS E:\Sample\Extra\Assert Demo› python -0 safe assert example.py 2The principal is 3 3The time period is time 4The rate of interest is 8 5Traceback (most recent call last): 6 File "E:\Sample\Extra\Assert Demo\safe assert example.py", line 12, in <module> simpleInterest(3, "time", 8) 7 File "E:\Sample\Extra\Assert Demo\safe assert example.py", line 8, in simpleInterest simpleInterest = (p * t * r)/100 8TypeError: unsupported operand type(s) for /: 'str' and 'int'
🌐
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 ...
🌐
BrowserStack
browserstack.com › home › guide › assert in python: what is it and how to use it
Assert in Python: What is it and How to use it | BrowserStack
July 4, 2025 - try: x = -10 assert x > 0, "x must be positive" except AssertionError as e: print(f"Assertion failed: {e}") ... When running Python with the -O (optimize) flag, assertions can be globally disabled.
🌐
Sonar Community
community.sonarsource.com › rules and languages › new rules / language support
Feature: Python assert should be consider harmful - New rules / language support - Sonar Community
February 11, 2021 - In python the assert statements are ignored when running in optimize mode. This can lead to code misbehaving in production because the wrong check is in place. An old thread on the topic but still relevant: We would l…
🌐
Python.org
discuss.python.org › ideas
Stop ignoring asserts when running in optimized mode - Page 3 - Ideas - Discussions on Python.org
January 19, 2022 - It may be useful to compare how C’s assert statement works. It is used in debug/testing phase for things that “should not happen”. (I like how @barry expressed it - “I never write assert s expecting them to ever be triggered”). One asserts that something is true - if it’s not then something is severely broken somewhere else.
Top answer
1 of 16
1769

The assert statement exists in almost every programming language. It has two main uses:

  1. It helps detect problems early in your program, where the cause is clear, rather than later when some other operation fails. A type error in Python, for example, can go through several layers of code before actually raising an Exception if not caught early on.

  2. It works as documentation for other developers reading the code, who see the assert and can confidently say that its condition holds from now on.

When you do...

assert condition

... you're telling the program to test that condition, and immediately trigger an error if the condition is false.

In Python, it's roughly equivalent to this:

if not condition:
    raise AssertionError()

Try it in the Python shell:

>>> assert True # nothing happens
>>> assert False
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AssertionError

Assertions can include an optional message, and you can disable them when running the interpreter.

To print a message if the assertion fails:

assert False, "Oh no! This assertion failed!"

Do not use parenthesis to call assert like a function. It is a statement. If you do assert(condition, message) you'll be running the assert with a (condition, message) tuple as first parameter.

As for disabling them, when running python in optimized mode, where __debug__ is False, assert statements will be ignored. Just pass the -O flag:

python -O script.py

See here for the relevant documentation.

2 of 16
632

Watch out for the parentheses. As has been pointed out in other answers, in Python 3, assert is still a statement, so by analogy with print(..), one may extrapolate the same to assert(..) or raise(..) but you shouldn't.

This is wrong:

assert(2 + 2 == 5, "Houston we've got a problem")

This is correct:

assert 2 + 2 == 5, "Houston we've got a problem"

The reason the first one will not work is that bool( (False, "Houston we've got a problem") ) evaluates to True.

In the statement assert(False), these are just redundant parentheses around False, which evaluate to their contents. But with assert(False,) the parentheses are now a tuple, and a non-empty tuple evaluates to True in a boolean context.

🌐
Thedeveloperblog
thedeveloperblog.com › python › assert-python
Python assert, O Option
assert(value + value2 != 110) print("DONE") Command line: C:\pypy3-2.4.0-win32\pypy.exe -O C:\programs\file.py Output DONE Command line: C:\pypy3-2.4.0-win32\pypy.exe C:\programs\file.py Output Traceback (most recent call last): File "C:\programs\file.py", line 8, in <module> assert(value + value2 != 110) AssertionError · Options. When running PyPy or Python, try providing the "-h" option. This will show you help. Then use "-O" to enable optimization (which removes asserts).