在关于__future__
的python文档中,下面的表格显示了
注释“在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'>}
我怀疑我不是很清楚这里的“可选输入”和“强制输入”的含义
答案 0 :(得分:14)
必填项是一个有趣的单词选择。我猜这意味着它是默认语言。您不必使用from __future__ import annotations
annotations
功能是指PEP 563:推迟注释的评估。这是对现有annotations feature的增强,它最初是在python 3.0中引入的,在python 3.5中被重新定义为type hints,这就是为什么您的代码在python 3.8下工作的原因。
以下是可选的from __future__ import annotations
在python 3.7+中的更改:
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一章,有关推迟注释的新功能:
由于此更改破坏了兼容性,因此需要使用
__future__
导入在Python 3.7中按模块启用新行为:
from __future__ import annotations
它将成为Python 3.10中的默认设置。
答案 1 :(得分:-1)
默认情况下必须提供。
可选,需要从from __future__ import annotations
语句“激活”