Tips and Tricks - When to Use NoReturn and When None

Let's assume we have a function, which has no real return value.

def greet():
    print("Hello World")

Should I annotate this function with typing.NoReturn, because no explicit return-statement was written? Technically seen, the function has a return-value: None. You can see it if you capture the return value of the built-in print() function:

value = print("Hello\n")
print(value)
# Hello
# None

Consequently, our greet() function needs to get the None return type annotated.

def greet() -> None:
    print("Hello World")

The type typing.NoReturn is meant to be used if something does really never return. This is the case in infinite loops, ...

from typing import NoReturn


def loop() -> NoReturn:
    while True:
        pass

... when the function terminates the script like sys.exit() or if an exception is raised:

from typing import NoReturn


def exc() -> NoReturn:
    raise ValueError("Let's terminate here...")

Groups: language reference