# Stop ignoring asserts when running in optimized mode

**URL:** <https://discuss.python.org/t/stop-ignoring-asserts-when-running-in-optimized-mode/13132>\
**Category:** Ideas\
**Created:** [January 13, 2022, 8:04pm UTC](https://discuss.python.org/t/stop-ignoring-asserts-when-running-in-optimized-mode/13132 "2022-01-13T20:04:27Z")\
**Posts on this page:** 1\
**Showing post:** 20

<div class="post-metadata">

**Author:** ![tiran](https://sea2.discourse-cdn.com/flex002/user_avatar/discuss.python.org/tiran/32/48_2.png) [@tiran](https://discuss.python.org/u/tiran)\
**Post date:** [January 14, 2022, 11:06am UTC](https://discuss.python.org/t/stop-ignoring-asserts-when-running-in-optimized-mode/13132/20 "2022-01-14T11:06:52Z")

</div>

> [@barry](#):
>
> How often do you think ` __debug__ ` blocks are used?

`if __debug__ ` blocks are rarely used. I have seen it in very few libraries, mostly older code. Over time developers realised that libraries were abusing `assert` for control flows, which made `python -O` unreliable.

> [@barry](#):
>
> Why does Django care whether users run with `-O` or not? Is there some fundamental functionality or assumption that breaks when users do that? It sounds like if that’s the case, then changing them to `raise` is the right thing to do regardless of whether `assert` gets no-op’d or not.

Part of the problem with `assert` is the fact that a failed assert does not abort the process. It’s too easy and too common to catch and ignore the result of a failed `assert`. Python’s `assert` should really work more like C `assert`. In C a failed [assert(3)](https://man7.org/linux/man-pages/man3/assert.3.html) results in an abnormal termination of the program. In Python `assert False` raises an `AssertionError`, which is a subclass of `Exception`. We should have changed the base class to `BaseException` or treat a failed assert as unrecoverable error (e.g. abort with `Py_FatalError`).

> [@barry](#):
>
> I never write `assert`s expecting them to _ever_ be triggered. Well, except for `pytest`s that is.
> 
> (Aside: this is the one aspect of pytest that bugged me for like forever, and stopped me from adopting it. But then I stopped trying to paddle upstream and now I’m fine with the pytest use of `assert` and certainly agree it makes writing tests a lot more readable than `self.assertBlah()` calls.)

Nathaniel explained to me that pytest’s use of `assert` is not affected by the optimized flag. He wrote:

> pytest transforms the source AST for test files before compilation, to replace `assert` s with annotated always-present assertions. that’s also how if you do `assert a == b` it can tell you what `a` and `b` were if it fails

---

_[View the full topic](https://discuss.python.org/t/stop-ignoring-asserts-when-running-in-optimized-mode/13132)._
