python3.0添加了注释,python3.5通过引入类型暗示(typehinting)在该特性的基础上进行了构建,使特性标准化。在
相关的PEP(Python增强建议)包括:
注释只是语法,类型提示是特定的功能。在
您可以将语法用于任何您喜欢的内容,如内联文档:def documentation(self: "the instance", arg1: "first argument") -> "nothing is returned":
pass
语法所做的只是将您提供的额外信息附加到函数对象:
^{pr2}$
类型提示规范指定如何使用这些注释来说明每个参数应该是什么类型以及返回什么。它是注释的具体应用,因为它定义了如何解释注释。在
类型提示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.
类型暗示仍然是完全可选的,现在不需要也永远不需要使用它。再次引用政治公众人物: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.
原文强调。在
您可以安装^{} module来向早期的python3.x版本添加类型暗示。在