Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading