Python doc __future__

在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发布时)被宣布为默认版本,但现在被转移到了更晚的版本

Python-3.x相关问答推荐

具有多个值的极轴旋转和熔化/取消旋转(反转旋转)操作(Pandas 堆叠/取消堆叠交替/UDF覆盖)

使用递归将int转换为字符串

我可以设置树视图层次 struct 按钮吗?

使用 iloc 或 loc 对多列进行过滤

Python Regex 查找给定字符串是否遵循交替元音、辅音或辅音、元音的连续模式

Jupyter Notebook 拒绝打印一些字符串

numpy是如何添加@运算符的?

是否可以将多个 if 转换为数组?

列表中的重复数字与列表理解

如何从 Python 3.5 降级到 Python 3.4

Tkinter 窗口显示(无响应)但代码正在运行

如何在 Python 中计算 cohen 的 d?

发送Electron邮件时的 MIMEText UTF-8 编码问题

如何在元素列表中找到最大的数字,可能是非唯一的?

Python:在 map 对象上调用列表两次

为 Python 3 和 PyQt 构建可执行文件

Python3 - 如何从现有抽象类定义抽象子类?

Windows 下 Python 3.x 的 OpenCV

如何将python日志(log)级别名称转换为整数代码

交错4个相同长度的python列表