在python doc about __future__
中,下面有一个表显示
>>> def add_int(a:int, b:int) -> int:
... return a + b
>>> add_int.__annotations__
{'a': <class 'int'>, 'b': <class 'int'>, 'return': <class 'int'>}
我怀疑我不清楚这里"可选"和"强制"的含义
在python doc about __future__
中,下面有一个表显示
>>> def add_int(a:int, b:int) -> int:
... return a + b
>>> add_int.__annotations__
{'a': <class 'int'>, 'b': <class 'int'>, 'return': <class 'int'>}
我怀疑我不清楚这里"可选"和"强制"的含义
强制性是一个有趣的词汇 Select .我猜这意味着它在语言中是默认的.你不必用from __future__ import annotations
启用它
annotations
特征指的是PEP 563:Postponed注释判断.这是对现有annotations feature的一个增强,它最初在python 3.0中引入,在python 3.5中重新定义为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 3.7中的this章延迟注释的新增功能:
由于此更改 destruct 了兼容性,因此需要在Python 3.7中使用
__future__
导入在每个模块的基础上启用新行为:
from __future__ import annotations
它将成为Python 3.10*中的默认值.
*它在3.10版本(python3.7发布时)被宣布为默认版本,但现在被转移到了更晚的版本