且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

什么是变量注解?

更新时间:2021-12-19 21:26:41

:= 之间的一切都是类型提示,所以 primes> 确实被定义为 List[int],并且最初设置为一个空列表(并且 stats 最初是一个空字典,定义为 Dict[str, int]).

Everything between : and the = is a type hint, so primes is indeed defined as List[int], and initially set to an empty list (and stats is an empty dictionary initially, defined as Dict[str, int]).

List[int]Dict[str, int] 不是下一个语法的一部分,但是,它们已经在 Python 3.5 类型提示 PEP 中定义.3.6 PEP 526 – 变量注释的语法提案 定义将相同提示附加到变量的语法;在您只能将类型提示附加到带有注释的变量之前(例如 primes = [] # List[int]).

List[int] and Dict[str, int] are not part of the next syntax however, these were already defined in the Python 3.5 typing hints PEP. The 3.6 PEP 526 – Syntax for Variable Annotations proposal only defines the syntax to attach the same hints to variables; before you could only attach type hints to variables with comments (e.g. primes = [] # List[int]).

ListDict 都是 Generic 类型,表示你有一个具有特定(具体)内容的列表或字典映射.

Both List and Dict are Generic types, indicating that you have a list or dictionary mapping with specific (concrete) contents.

对于List,只有一个参数"([...] 语法中的元素),即列表中每个元素的类型.对于 Dict,第一个参数是键类型,第二个参数是值类型.所以primes列表中的所有值都是整数,而stats字典中的所有键值对是(str, int) 对,将字符串映射到整数.

For List, there is only one 'argument' (the elements in the [...] syntax), the type of every element in the list. For Dict, the first argument is the key type, and the second the value type. So all values in the primes list are integers, and all key-value pairs in the stats dictionary are (str, int) pairs, mapping strings to integers.

请参阅typing.Listtyping.Dict 定义,关于泛型的部分,以及PEP 483 – 类型提示理论.

就像函数的类型提示一样,它们的使用是可选的,也被认为是注解(前提是有一个对象可以附加它们,所以模块中的全局变量和类的属性,而不是函数中的局部变量) 您可以通过 __annotations__ 属性进行内省.您可以将任意信息附加到这些注释中,您并不仅限于键入提示信息.

Like type hints on functions, their use is optional and are also considered annotations (provided there is an object to attach these to, so globals in modules and attributes on classes, but not locals in functions) which you could introspect via the __annotations__ attribute. You can attach arbitrary info to these annotations, you are not strictly limited to type hint information.

您可能需要阅读完整提案;它包含一些超出新语法的附加功能;例如,它指定何时评估此类注释、如何内省它们以及如何将某些内容声明为类属性与实例属性.

You may want to read the full proposal; it contains some additional functionality above and beyond the new syntax; it specifies when such annotations are evaluated, how to introspect them and how to declare something as a class attribute vs. instance attribute, for example.