Python 以字符串形式给出类型提示?
Python type hint given as a string?
我有这种形式的功能:
def foo(o: "hello") -> dict:
# pass
我理解“-> dict”表示 foo returns 字典。我不明白的是 "hello" 部分。为什么这种类型提示以字符串的形式给出? "hello" 是什么?
可能相关 - 这是一个自动生成的文件。
有时需要在创建对象之前设置类型注释,例如:
class Node:
def next() -> Node:
pass
这段代码实际上失败了,因为 Node
被引用为 Node.next
的注释,而 class Node
仍在创建中。这与以下失败的原因相同:
class T:
t = T()
要解决这个问题,您可以改用字符串
class Node:
def next() -> 'Node':
pass
所以类型检查器只会在稍后计算 Node
(forward reference)。
这实际上 decided 是一个设计缺陷,因此在 python 3.7 中,您可以使用 from __future__ import annotations
,第一个示例将起作用。
编辑 2022 年 4 月
自从创建以来,发生了很多变化(但也有很多没有)。最重要的区别是字符串 annotations
是从 py 3.10 推迟的,它 sounds like it will never be stabilized. Instead the steering committee will probably end up stabilizing PEP 649 具有稍微复杂的行为,但仍然支持自引用类型提示。有关详细信息,请参阅 PEP。
我有这种形式的功能:
def foo(o: "hello") -> dict:
# pass
我理解“-> dict”表示 foo returns 字典。我不明白的是 "hello" 部分。为什么这种类型提示以字符串的形式给出? "hello" 是什么?
可能相关 - 这是一个自动生成的文件。
有时需要在创建对象之前设置类型注释,例如:
class Node:
def next() -> Node:
pass
这段代码实际上失败了,因为 Node
被引用为 Node.next
的注释,而 class Node
仍在创建中。这与以下失败的原因相同:
class T:
t = T()
要解决这个问题,您可以改用字符串
class Node:
def next() -> 'Node':
pass
所以类型检查器只会在稍后计算 Node
(forward reference)。
这实际上 decided 是一个设计缺陷,因此在 python 3.7 中,您可以使用 from __future__ import annotations
,第一个示例将起作用。
编辑 2022 年 4 月
自从创建以来,发生了很多变化(但也有很多没有)。最重要的区别是字符串 annotations
是从 py 3.10 推迟的,它 sounds like it will never be stabilized. Instead the steering committee will probably end up stabilizing PEP 649 具有稍微复杂的行为,但仍然支持自引用类型提示。有关详细信息,请参阅 PEP。