3.3 和 3.5 中的类型提示有什么区别?

What's the difference between type hinting in 3.3 and 3.5?

我一直听说类型提示将成为 3.5 中的一项新功能,但这让我想知道 3.3 中的箭头指示器 (->) 是什么?

您可以在 3.3 grammar spec here, which I found from this question asked 2 years ago.

中看到它

我想知道,类型提示以前是否存在,但形式有限,而 3.5 带来了更多的主要支持?还是我对类型提示的理解不正确,它实际上有其他含义?

-> 用于注释One of the use cases for annotations 是类型提示。

Python 3.0 添加了注释,Python 3.5 通过引入类型提示和标准化功能建立在该功能的基础上。

相关 PEP(Python 增强提案)是:

注解只是语法,类型提示是特定功能

您可以将语法用于任何您喜欢的内容,例如内联文档:

def documentation(self: "the instance", arg1: "first argument") -> "nothing is returned":
    pass

语法所做的就是将您提供的额外信息附加到函数对象:

>>> def documentation(self: "the instance", arg1: "first argument") -> "nothing is returned":
...     pass
... 
>>> documentation.__annotations__
{'return': 'nothing is returned', 'arg1': 'first argument', 'self': 'the instance'}

类型提示规范指定了如何使用这些注释来说明每个参数应该是什么类型以及返回什么。它是注释的特定应用,因为它定义了如何解释注释。

Type Hinting PEP 明确指出它并不是注释的唯一用途:

Note that this PEP still explicitly does NOT prevent other uses of annotations, nor does it require (or forbid) any particular processing of annotations, even when they conform to this specification. It simply enables better coordination, as PEP 333 did for web frameworks.

类型提示仍然是完全可选的,它不是也永远不会被要求使用它。再次引用 PEP:

While the proposed typing module will contain some building blocks for runtime type checking -- in particular the get_type_hints() function -- third party packages would have to be developed to implement specific runtime type checking functionality, for example using decorators or metaclasses. Using type hints for performance optimizations is left as an exercise for the reader.

It should also be emphasized that Python will remain a dynamically typed language, and the authors have no desire to ever make type hints mandatory, even by convention.

强调原文。

您可以安装 typing module 以向早期 Python 3.x 版本添加类型提示。