Search code examples
pythonpython-typing

Is typing.assert_never() removed by command line option -O, similar to assert statement?


In Python, assert statement produces no code if command line optimization options -O or -OO are passed. Does it happen for typing.assert_never()? Is it safe to declare runtime assertions that will not be optimized out?

Consider the case

from typing import assert_never

def func(item: int | str):
    match item:
        case int():
            ...
        case str():
            ...
        case _:
            assert_never(item)

Is it guaranteed that the default branch will work even in optimized mode?


Solution

  • No. assert_never() is only a normal function consisting of a raise statement, at least in CPython. It is not removed at runtime, as with other typing features.


    It should be emphasized that assert_never() has nothing special: It just takes in an argument of type Never and never returns anything (i.e., it raises):

    def assert_never(arg: Never) -> Never:
        raise AssertionError("Expected code to be unreachable")
    

    Its inclusion in the stdlib was simply due to the expectation that it would be commonly used. To quote the typing guides:

    Because the assert_never() helper function is frequently useful, it is provided by the standard library as typing.assert_never starting in Python 3.11, and is also present in typing_extensions starting at version 4.1.

    § assert_never() and Exhaustiveness Checking | Python typing guides

    The same section also says:

    However, it is also possible to define a similar function in your own code, for example if you want to customize the runtime error message.