PEP 484: Add NoReturn type (#218)

As discussed in python/typing#165.
This commit is contained in:
Ivan Levkivskyi 2017-03-17 21:46:55 +01:00 committed by Guido van Rossum
parent 0789423c46
commit 881c6bebdb
1 changed files with 47 additions and 0 deletions

View File

@ -1063,6 +1063,53 @@ in turn, to ``collections.abc.Callable``::
...
The ``NoReturn`` type
---------------------
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 ``NoReturn`` annotation is used for functions such as ``sys.exit``.
Static type checkers will ensure that functions annotated as returning
``NoReturn`` truly never return, either implicitly or explicitly::
import sys
from typing import NoReturn
def f(x: int) -> NoReturn: # Error, f(0) implicitly returns None
if x != 0:
sys.exit(1)
The checkers will also recognize that the code after calls to such functions
is unreachable and will behave accordingly::
# continue from first example
def g(x: int) -> int:
if x > 0:
return x
stop()
return 'whatever works' # Error might be not reported by some checkers
# that ignore errors in unreachable blocks
The ``NoReturn`` type is only valid as a return annotation of functions,
and considered an error if it appears in other positions::
from typing import List, NoReturn
# All of the following are errors
def bad1(x: NoReturn) -> int:
...
bad2 = None # type: NoReturn
def bad3() -> List[NoReturn]:
...
The type of class objects
-------------------------