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 - You can disable all your assert statements by having the __debug__ constant set to False. To accomplish this task, you can use Python’s -O or -OO command-line options to run the interpreter in optimized mode.
Discussions

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
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
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
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
🌐
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 ...
🌐
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…
🌐
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
🌐
Python.org
discuss.python.org › ideas
Stop ignoring asserts when running in optimized mode - Page 3 - Ideas - Discussions on Python.org
January 19, 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 …
Find elsewhere
🌐
Reddit
reddit.com › r/python › why you should never use 'assert' in python
r/Python on Reddit: Why you should never use 'assert' in Python
November 9, 2018 - You can use the -O or -OO switches on the Python command to reduce the size of a compiled module. The -O switch removes assert statements, the -OO switch removes both assert statements and __doc__ strings.
🌐
Snyk
snyk.io › blog › the-dangers-of-assert-in-python
The dangers of assert in Python | Snyk
August 18, 2022 - In this example, assertion helped us debug our program and stopped the program’s execution as soon as the assertion failed. Recall that running the program in optimized mode (by setting the PYTHONOPTIMIZE command line flag, -O) silently disables assert statements.
🌐
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).
🌐
Dot Net Perls
dotnetperls.com › assert-python
Python - assert, O Option - Dot Net Perls
This statement causes an AssertionError ... 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....
🌐
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).
🌐
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).
🌐
GitHub
github.com › MDAnalysis › mdanalysis › issues › 724
tests should not use a Python `assert` statement but instead use `numpy.testing.assert_` · Issue #724 · MDAnalysis/mdanalysis
February 15, 2016 - Accepts callable msg to allow deferring evaluation until failure. The Python built-in ``assert`` does not work when executing code in optimized mode (the ``-O`` flag) - no byte-code is generated for it.
Author   orbeckst
Top answer
1 of 5
83

I guess the main reason for assert not being used more often is that nobody uses Python's "optimized" mode.

Asserts are a great tool to detect programming mistakes, to guard yourself from unexpected situations, but all this error checking comes with a cost. In compiled languages such as C/C++, this does not really matter, since asserts are only enabled in debug builds, and completely removed from release builds.

In Python, on the other hand, there is no strict distinction between debug and release mode. The interpreter features an "optimization flag" (-O), but currently this does not actually optimize the byte code, but only removes asserts.

Therefore, most Python users just ignore the -O flag and run their scripts in "normal mode", which is kind of the debug mode since asserts are enabled and __debug__ is True, but is considered "production ready".

Maybe it would be wiser to switch the logic, i.e., "optimize" by default and only enable asserts in an explicit debug mode(*), but I guess this would confuse a lot of users and I doubt we will ever see such a change.

((*) This is for example how the Java VM does it, by featuring a -ea (enable assertions) switch.)

2 of 5
38

Several reasons come to mind...

It is not a primary function

Many programmers, lets not get bogged down by the rationale, disrespect anything which is not a direct participant in the program's penultimate functionality. The assert statement is intended for debugging and testing, and so, a luxury they can ill-afford.

Unit Testing

The assert statement predates the rise and rise of unit-testing. Whilst the assert statement still has its uses, unit-testing is now widely used for constructing a hostile environment with which to bash the crap out of a subroutine and its system. Under these conditions assert statements start to feel like knives in a gunfight.

Improved industry respect for testing

The assert statement serves best as the last line of defence. It rose to lofty and untouchable heights under the C language, when that language ruled the world, as a great way to implement the new-fangled "defensive programming"; it recognises and traps catastrophic disasters in the moment they teeter on the brink. This was before the value of Testing became widely recognised and respected and disasters were substantially more common.

Today, it is unheard of, for any serious commercial software to be released without some form of testing. Testing is taken seriously and has evolved into a massive field. There are Testing professionals and Quality Assurance departments with big checklists and formal sign-offs. Under these conditions programmers tend not to bother with asserts because they have confidence that their code will be subjected to so much tiresome testing that the odds of wacky brink-of-disaster conditions are so remote as to be negligible. That's not to say they're right, but if the blame for lazy programming can be shifted to the QA department, hell why not?

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.

🌐
Python.org
discuss.python.org › ideas
Stop ignoring asserts when running in optimized mode - Page 2 - Ideas - Discussions on Python.org
January 14, 2022 - It’s sensible to catch an AssertionError to, for example, bring down the system orderly, leaving it in a consistent state. If the program is properly modularized, then the error could shut down only the affected module and alert operators.
🌐
Medium
codereviewdoctor.medium.com › you-might-be-using-assert-wrong-6a9daf821a03
You might be using assert wrong. Assert is often used in production code… | by Code Review Doctor | Medium
August 9, 2022 - With this knowledge, we can view the compiled byte code of optimized and non-optimized: python3 -c 'import dis; dis.dis("assert 80 < 70")' 1 0 LOAD_CONST 0 (80) 2 LOAD_CONST 1 (70) 4 COMPARE_OP 0 (<) 6 POP_JUMP_IF_TRUE 6 (to 12) 8 LOAD_ASSERTION_ERROR 10 RAISE_VARARGS 1 >> 12 LOAD_CONST 2 (None) 14 RETURN_VALUEpython3 -O -c 'import dis; dis.dis("assert 80 < 70")' 1 0 LOAD_CONST 0 (None) 2 RETURN_VALUEPYTHONOPTIMIZE=1 python3 -c 'import dis; dis.dis("assert 80 < 70")' 1 0 LOAD_CONST 0 (None) 2 RETURN_VALUE