parent
0789423c46
commit
881c6bebdb
47
pep-0484.txt
47
pep-0484.txt
|
@ -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
|
The type of class objects
|
||||||
-------------------------
|
-------------------------
|
||||||
|
|
||||||
|
|
Loading…
Reference in New Issue