python - 什么是变量注解?

标签 python python-3.x type-hinting python-typing

Python 3.6 即将发布。 PEP 494 -- Python 3.6 Release Schedule提到12月底,所以我通过了What's New in Python 3.6看到他们提到了变量注释:

PEP 484 introduced standard for type annotations of function parameters, a.k.a. type hints. This PEP adds syntax to Python for annotating the types of variables including class variables and instance variables:

primes: List[int] = []

captain: str  # Note: no initial value!

class Starship:
     stats: Dict[str, int] = {}

Just as for function annotations, the Python interpreter does not attach any particular meaning to variable annotations and only stores them in a special attribute __annotations__ of a class or module. In contrast to variable declarations in statically typed languages, the goal of annotation syntax is to provide an easy way to specify structured type metadata for third party tools and libraries via the abstract syntax tree and the __annotations__ attribute.

所以从我读到的内容来看,它们是来自 Python 3.5 的类型提示的一部分,在 What are Type hints in Python 3.5 中进行了描述。 .

我遵循 captain: strclass Starship 示例,但不确定最后一个:primes: List[int] = [] 如何 解释一下?它是否定义了一个只允许整数的空列表?

最佳答案

What are variable annotations?

变量注释只是 # type 的下一步评论,正如它们在 PEP 484 中定义的那样; respective section of PEP 526 中强调了此更改背后的基本原理。 .

所以,不要用以下方式提示类型:

primes = []  # type: List[int]

引入了新语法以允许使用以下形式的赋值直接注释类型:

primes: List[int] = []

正如@Martijn 所指出的,它使用 typing 中可用的类型来表示整数列表。并将其初始化为一个空列表。

What changes does it bring?

引入的第一个更改是 new syntax允许您使用类型注释名称,可以在 : 之后独立使用字符或可选注释,同时也为其赋值:

annotated_assignment_stmt ::=  augtarget ":" expression ["=" expression]

所以有问题的例子:

   primes: List[int] = [ ]
#    ^        ^         ^
#  augtarget  |         |
#         expression    |
#                  expression (optionally initialize to empty list)

还引入了其他更改以及新语法;模块和类现在有 __annotations__附加类型元数据的属性(就像函数自 PEP 3107 -- Function Annotations 以来所具有的那样):

from typing import get_type_hints  # grabs __annotations__

现在 __main__.__annotations__持有声明的类型:

>>> from typing import List, get_type_hints
>>> primes: List[int] = []
>>> captain: str
>>> import __main__
>>> get_type_hints(__main__)
{'primes': typing.List<~T>[int]}

captain目前不会通过 get_type_hints 显示因为get_type_hints仅返回也可以在模块上访问的类型;即,它首先需要一个值:

>>> captain = "Picard"
>>> get_type_hints(__main__)
{'primes': typing.List<~T>[int], 'captain': <class 'str'>}

使用 print(__annotations__)将显示 'captain': <class 'str'>但你真的不应该访问 __annotations__直接。

同样,对于类:

>>> get_type_hints(Starship)
ChainMap({'stats': typing.Dict<~KT, ~VT>[str, int]}, {})

在哪里 ChainMap用于获取给定类的注解(位于第一个映射中)以及在其mro 中找到的基类中定义的所有注解。 (后续映射,{} 用于对象)。

与新语法一起,新的 ClassVar 已添加类型以表示类变量。是的,stats在您的示例中实际上是 实例变量,而不是 ClassVar .

Will I be forced to use it?

与来自 PEP 484 的类型提示一样,这些是完全可选的,主要用于类型检查工具(以及您可以基于此信息构建的任何其他工具)。当 Python 3.6 的稳定版本发布时,它是临时的,因此将来可能会添加一些小的调整。

关于python - 什么是变量注解?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39971929/

相关文章:

python - 使用 re(正则表达式)仅解析一行

python - 是否可以创建受正则表达式约束的类型提示?

Python:类名中的双冒号

python - MPI 分散分布大型 csv 文件

python - opencv 的段错误,在 Raspberry 上的 python 中

python - 如何在aiohttp中发回图像/文件

python - 将字典列表转换为列表列表

python-3.x - 在 python C api 中将可迭代对象转换为元组

Python:自动完成可以用于列表中的元素吗?

python 3 : type inferencing with mypy?