Search code examples
pythonpython-typing

Type hint that a function never returns


Python's new type hinting feature allows us to type hint that a function returns None...

def some_func() -> None:
    pass

... or to leave the return type unspecified, which the PEP dictates should cause static analysers to assume that any return type is possible:

Any function without annotations should be treated as having the most general type possible

However, how should I type hint that a function will never return? For instance, what is the correct way to type hint the return value of these two functions?

def loop_forever():
    while True:
        print('This function never returns because it loops forever')

def always_explode():
    raise Exception('This function never returns because it always raises')

Neither specifying -> None nor leaving the return type unspecified seems correct in these cases.


Solution

  • Even though “PEP 484 — Type Hints” standard mentioned both in question and in the answer yet nobody quotes its section: The NoReturn type that covers your question.

    Quote:

    The typing module provides a special type NoReturn to annotate functions that never return normally. For example, a function that unconditionally raises an exception:

    from typing import NoReturn
    
    def stop() -> NoReturn:
        raise RuntimeError('no way')
    

    The section also provides examples of the wrong usages. Though it doesn’t cover functions with an endless loop, in type theory they both equally satisfy never returns meaning expressed by that special type.