NoReturn vs. None in “void” functions - type annotations in Python 3.6

拟墨画扇 提交于 2020-05-28 13:36:59

问题


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

回答1:


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) and os.exit (which never returns)..



来源:https://stackoverflow.com/questions/48038149/noreturn-vs-none-in-void-functions-type-annotations-in-python-3-6

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!