The NoReturn type

Mypy provides support for functions that never return. Forexample, a function that unconditionally raises an exception:

  1. from typing import NoReturn
  2.  
  3. def stop() -> NoReturn:
  4. raise Exception('no way')

Mypy will ensure that functions annotated as returning NoReturntruly never return, either implicitly or explicitly. Mypy will alsorecognize that the code after calls to such functions is unreachableand will behave accordingly:

  1. def f(x: int) -> int:
  2. if x == 0:
  3. return x
  4. stop()
  5. 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:

  1. python3 -m pip install --upgrade typing-extensions

This works for Python 2:

  1. pip install --upgrade typing-extensions