The NoReturn type
Mypy provides support for functions that never return. Forexample, a function that unconditionally raises an exception:
- from typing import NoReturn
- def stop() -> NoReturn:
- raise Exception('no way')
Mypy will ensure that functions annotated as returning NoReturn
truly never return, either implicitly or explicitly. Mypy will alsorecognize that the code after calls to such functions is unreachableand will behave accordingly:
- def f(x: int) -> int:
- if x == 0:
- return x
- stop()
- return 'whatever works' # No error in an unreachable block
In earlier Python versions you need to install typing_extensions
usingpip to use NoReturn
in your code. Python 3 command line:
- python3 -m pip install --upgrade typing-extensions
This works for Python 2:
- pip install --upgrade typing-extensions