来自 __future__ 导入注释

from __future__ import annotations

Python doc __future__

在关于 __future__ 的 python 文档中,下面有一个 table 显示 3.7.0b1 中的“可选”注释和 4.0 中的“强制性”注释 但我仍然可以在 3.8.2 中使用注释而无需导入注释,那么它有什么用呢。

>>> def add_int(a:int, b:int) -> int:
...     return a + b
>>> add_int.__annotations__
{'a': <class 'int'>, 'b': <class 'int'>, 'return': <class 'int'>}

我怀疑我没有清楚地理解这里的“optional in”和“mandatory in”的意思

强制性是一个有趣的用词选择。我想这意味着它在语言中是默认的。您不必使用 from __future__ import annotations

启用它

annotations 特性指的是 PEP 563:推迟 注释评估。它是对 python 3.5 中现有 annotations feature which was initially introduced in python 3.0 and redefined as type hints 的增强,这就是为什么您的代码在 python 3.8.

下工作的原因

以下是 python 3.7+ 中的可选 from __future__ import annotations 更改:

class A:
    def f(self) -> A: # NameError: name 'A' is not defined
        pass

但这行得通

from __future__ import annotations

class A:
    def f(self) -> A:
        pass

请参阅 python 中的 this 章节 3.7 关于推迟注释的新内容:

Since this change breaks compatibility, the new behavior needs to be enabled on a per-module basis in Python 3.7 using a __future__ import:

from __future__ import annotations

It will become the default in Python 3.10*.

* 它在 3.10 中被宣布为默认值(当 python3.7 发布时),但现在已移至更高版本

默认情况下必填。 可选,因为需要从 from __future__ import annotations 语句

中“激活”