Python Glossary Русский

Python 3.11+typingfunction

typing.assert_never

casting and debugging

Marks an unreachable branch (e.g. in an exhaustive match): a type checker proves it unreachable, and at run time it always raises AssertionError (3.11+).

Syntax

typing.assert_never(value)

A trick for exhaustive match or if-elif chains: in the final, supposedly unreachable branch the type checker verifies no case can reach it, and the moment you add a new variant it flags this exact call. At runtime it does nothing useful — reaching it already means a bug, so it always raises AssertionError.

Examples

from typing import assert_never
try:
    assert_never(1)
except AssertionError:
    print('unreachable')   # → unreachable

See also

Common errors

Open in the full glossarydocs.python.orgReport an inaccuracy