python - "void"函数中的 NoReturn 与 None - Python 3.6 中的类型注释

标签 python annotations python-3.6 type-hinting typing

Python 3.6 支持类型注释,例如:

def foo() -> int:
    return 42

但是当一个函数没有返回任何东西时,期望使用什么? PEP484示例主要使用 None 作为返回类型,但也有来自 typing 包的 NoReturn 类型。

因此,问题是什么更适合使用以及什么被认为是最佳实践:

def foo() -> None:
    #do smth

from typing import NoReturn

def foo() -> NoReturn:
    #do smth

最佳答案

NoReturn 表示函数从不返回值

函数不会终止或总是抛出异常:"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')

也就是说,x = foo_None() 是类型有效的,但值得怀疑,而 x = foo_NoReturn() 是无效的。

除了从来没有可分配的结果,NoReturn 在分支分析中还有其他含义:foo_NoReturn();无法访问..'A NoReturn type is needed #165' 中有进一步的讨论门票。

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)..

关于python - "void"函数中的 NoReturn 与 None - Python 3.6 中的类型注释,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48038149/

相关文章:

python - 在Python中读写TOML时为什么要使用二进制模式?

python - 在 Django 中截断 SQL 查询的日志记录

python - 如何只打印字符串中的特定单词

java - Spring自定义注解集成测试

jpa - 通过未标记为级联 PERSIST 的关系找到了新对象

python - cx_Freeze 没有找到一些 TensorFlow 导入

python - 无法从登录页面进一步移动,[django-otp]

java - 带注释的 EhCache 配置 - Hibernate

使用 python c-api 的 Python3 重新加载项目

python - 使用 Web 服务时无法 pickle _thread.RLock 对象