Python 3.6 supports type annotation, like:
def foo() -> int: return 42
But what is expected to use when a function hasn't return anything? PEP484 examples mostly use None
as a return type, but there is also NoReturn
type from typing
package.
So, the question is what is preferable to use and what is considered a best practice:
def foo() -> None: #do smth
or
from typing import NoReturn def foo() -> NoReturn: #do smth
NoReturn means the function never returns a value. The function either does not terminate or always throws an exception: "The typing module provides a special type NoReturn to annotate functions that never return normally. For example, a function that unconditionally raises an exception..".
In Python, it is possible to compose a function without a return statement. Functions like this are called void, and they return None, Python's special object for "nothing". Here's an example of a void function: >>> def sayhello(who): print 'Hello,', who + '!'
NoReturn
means the function never returns a value.
The function either does not terminate or always throws an exception: "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')
That is, x = foo_None()
is type-valid but suspect while x = foo_NoReturn()
is invalid.
Besides never having an assignable result, NoReturn
also has other implications in branch analysis: foo_NoReturn(); unreachable..
. There is further discussion in the 'A NoReturn
type is needed #165' ticket.
In order to perform branch analysis, it is necessary to know which calls will never return normally. Examples are
sys.exit
(which always returns via exception) andos.exit
(which never returns)..
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With