Python void return 类型注解

Python void return type annotation

在python3.x中,常用函数的return类型注解,如:

def foo() -> str:
    return "bar"

"void" 类型的正确注释是什么?

我正在考虑 3 个选项:

  1. def foo() -> None:
    • IMO 不合逻辑,因为 None 不是类型,
  2. def foo() -> type(None):
    • 使用我所知道的最佳语法获取 NoneType,
  3. def foo():
    • 省略显式 return 类型信息。

选项 2. 对我来说似乎是最合乎逻辑的,但我已经看到了 1.

的一些实例

这直接来自 PEP 484 -- Type Hints 文档:

When used in a type hint, the expression None is considered equivalent to type(None).

而且,如您所见,大多数示例使用 None 作为 return 类型。

TLDR:void return 类型注释的惯用等价物是 -> None.

def foo() -> None:
    ...

这与没有 return 或只有 return 的函数的计算结果相匹配 None.

def void_func():  # unannotated void function
    pass

print(void_func())  # None

省略 return 类型 而不是 意味着没有 return 值。根据 PEP 484:

For a checked function, the default annotation for arguments and for the return type is Any.

这意味着该值被视为动态类型和静态类型 supports any operation。这实际上是 void.

的相反含义

Type-hinting in Python 并不严格要求实际类型。例如,注解可能使用类型名称的字符串:Union[str, int]Union[str, 'int']'Union[str, int]',各种变体是等价的。

同样,类型注释 None 被认为 表示 “属于 NoneType”。这可以用于其他情况以及 return 类型,尽管您最常看到它作为 return-type 注释:

bar : None

def foo(baz: None) -> None:
    return None

这也适用于泛型。例如,您可以在 Generator[int, None, None] 中使用 None 来指示生成器不采用或 return 值。


即使 PEP 484 建议 None 表示 type(None),您 不应该 明确使用后一种形式。 type-hinting 规范 包括任何形式的 type(...)。这在技术上是一个运行时表达式,它的支持完全取决于类型检查器。 mypy 项目是 considering whether to remove support for type(None) 并将其从 484 中删除。

Or maybe we should update PEP 484 to not suggest that type(None) is valid as a type, and None is the only correct spelling? There should one -- and preferably only one -- obvious way to do it etc.

--- JukkaL, 18 May 2018