Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 642
Mark Amery Avatar asked Jul 25 '16 14:07

Mark Amery


People also ask

Can a function have no return statement?

If no return statement appears in a function definition, control automatically returns to the calling function after the last statement of the called function is executed. In this case, the return value of the called function is undefined.

Does Python enforce type hints?

The Python runtime does not enforce function and variable type annotations. They can be used by third party tools such as type checkers, IDEs, linters, etc. This module provides runtime support for type hints. The most fundamental support consists of the types Any , Union , Callable , TypeVar , and Generic .

What is the point of type hinting?

Type hints improve IDEs and linters. They make it much easier to statically reason about your code. Type hints help you build and maintain a cleaner architecture. The act of writing type hints forces you to think about the types in your program.

What is type hint?

Type hinting is a formal solution to statically indicate the type of a value within your Python code. It was specified in PEP 484 and introduced in Python 3.5.


1 Answers

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.

like image 147
kuza Avatar answered Oct 05 '22 07:10

kuza