且构网

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

什么是变量注释?

更新时间:2022-05-22 15:15:23

: = 之间的所有内容都是类型提示,因此 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]).

List Dict 均为 Generic 类型,表示您具有具有特定(具体)内容的列表或字典映射.

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

对于 List ,只有一个参数"( [...] 语法中的元素),即列表中每个元素的类型.对于 Dict ,第一个参数是键类型,第二个参数是值类型.因此, primes 列表中的 all 值是整数,而 stats 字典中的 all 键值对是(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.List typing.Dict 定义, PEP 483 – 类型提示理论 .

See the typing.List and typing.Dict definitions, the section on Generics, as well as PEP 483 – The Theory of Type Hints.

类似于函数上的类型提示,它们的使用是可选的,并且也被视为注释(前提是存在将它们附加到的对象,因此模块中的全局变量和类的属性,但函数中的局部变量不是),您可以通过 __ 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.