Python 简明教程
Python - Function Annotations
Function Annotations
Python 的函数注解功能使您能够添加有关函数定义中声明的参数和返回数据类型的附加说明性元数据。在执行 function 时, Python interpreter 并未考虑它们。它们主要用于 Python IDE,以便向程序员提供详细文档。
The function annotation feature of Python enables you to add additional explanatory metadata about the arguments declared in a function definition, and also the return data type. They are not considered by Python interpreter while executing the function. They are mainly for the Python IDEs for providing a detailed documentation to the programmer.
尽管您可以使用 Python 的 docstring 功能来对函数进行文档记录,但在函数的原型做出某些更改时,它可能变得过时。因此,注释功能作为 PEP 3107 的结果引入 Python。
Although you can use the docstring feature of Python for documentation of a function, it may be obsolete if certain changes in the function’s prototype are made. Hence, the annotation feature was introduced in Python as a result of PEP 3107.
注释是可以添加到参数或返回数据类型的任何有效的 Python 表达式。注释最简单的示例是规定参数的数据类型。注释在参数前面加冒号后以表达式的形式提及。
Annotations are any valid Python expressions added to the arguments or return data type. Simplest example of annotation is to prescribe the data type of the arguments. Annotation is mentioned as an expression after putting a colon in front of the argument.
Example
请记住,Python 是一种动态类型语言,并且在运行时不执行任何类型检查。因此,在调用函数时用 data types 注释参数没有任何效果。即使给出了非整数参数,Python 也不会检测到任何错误。
Remember that Python is a dynamically typed language, and doesn’t enforce any type checking at runtime. Hence annotating the arguments with data types doesn’t have any effect while calling the function. Even if non-integer arguments are given, Python doesn’t detect any error.
def myfunction(a: int, b: int):
c = a+b
return c
print (myfunction(10,20))
print (myfunction("Hello ", "Python"))
它将生成以下 output −
It will produce the following output −
30
Hello Python
Function Annotations With Return Type
注释在运行时会被忽略,但对于 IDE 和 mypy 等静态类型检查器库很有用。
Annotations are ignored at runtime, but are helpful for the IDEs and static type checker libraries such as mypy.
您还可以为返回数据类型提供注释。在括号后面和冒号符号前面,加上一个箭头 (→),后跟注释。
You can give annotation for the return data type as well. After the parentheses and before the colon symbol, put an arrow (→) followed by the annotation.
Example
在此示例中,我们为返回类型提供注释。
In this example, we are providing annotation for return type.
def myfunction(a: int, b: int) -> int:
c = a+b
return c
print(myfunction(56,88))
print(myfunction.__annotations__)
这会产生以下输出 −
This will generate the following output −
144
{'a': <class 'int'>, 'b': <class 'int'>, 'return': <class 'int'>}
Function Annotations With Expression
由于在运行时忽略了使用数据类型作为注释,因此可以放置充当参数元数据的任何表达式。因此,函数可以具有任何任意的表达式作为注释。
As using the data type as annotation is ignored at runtime, you can put any expression which acts as the metadata for the arguments. Hence, function may have any arbitrary expression as annotation.
Example
在以下示例中,我们将表达式用作函数注释。
In the below example, we are using expression as a function annotation.
def total(x : 'marks in Physics', y: 'marks in chemistry'):
return x+y
print(total(86, 88))
print(total.__annotations__)
输出如下:
Following is the output −
174
{'x': 'marks in Physics', 'y': 'marks in chemistry'}
Function Annotations With Default Arguments
如果您想指定一个 default argument 与注释一起,您需要将其放在注释表达式之后。在参数列表中,默认参数必须位在需要的参数之后。
If you want to specify a default argument along with the annotation, you need to put it after the annotation expression. Default arguments must come after the required arguments in the argument list.
Example 1
以下示例演示如何为函数的默认参数提供注释。
The following example demonstrates how to provide annotation for default arguments of a function.
def myfunction(a: "physics", b:"Maths" = 20) -> int:
c = a+b
return c
print (myfunction(10))
Python 中的函数也是一个 object ,其中之一的属性是 annotations 。您可以用 dir() 函数检查。
The function in Python is also an object, and one of its attributes is annotations. You can check with dir() function.
print (dir(myfunction))
这将打印包含 annotations 作为其中一个属性的 myfunction 对象的列表。
This will print the list of myfunction object containing annotations as one of the attributes.
['__annotations__', '__builtins__', '__call__', '__class__', '__closure__', '__code__', '__defaults__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__get__', '__getattribute__', '__getstate__', '__globals__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__kwdefaults__', '__le__', '__lt__', '__module__', '__name__', '__ne__', '__new__', '__qualname__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__']
Example 2
annotations 属性本身是一个 dictionary ,其中参数是键,注释是它们的值。
The annotations attribute itself is a dictionary in which arguments are keys and anotations their values.
def myfunction(a: "physics", b:"Maths" = 20) -> int:
c = a+b
return c
print (myfunction.__annotations__)
它将生成以下 output −
It will produce the following output −
{'a': 'physics', 'b': 'Maths', 'return': <class 'int'>}
Example 3
您可以为函数指定任意位置和/或任意关键字参数。也可以为它们提供注释。
You may have arbitrary positional and/or arbitrary keyword arguments for a function. Annotations can be given for them also.
def myfunction(*args: "arbitrary args", **kwargs: "arbitrary keyword args") -> int:
pass
print (myfunction.__annotations__)
它将生成以下 output −
It will produce the following output −
{'args': 'arbitrary args', 'kwargs': 'arbitrary keyword args', 'return': <class 'int'>}
Example 4
如果您需要为函数参数提供多个注释表达式,请以字典对象的形式将其放在参数本身前面。
In case you need to provide more than one annotation expressions to a function argument, give it in the form of a dictionary object in front of the argument itself.
def division(num: dict(type=float, msg='numerator'), den: dict(type=float, msg='denominator')) -> float:
return num/den
print (division.__annotations__)
它将生成以下 output −
It will produce the following output −
{'num': {'type': <class 'float'>, 'msg': 'numerator'}, 'den': {'type': <class 'float'>, 'msg': 'denominator'}, 'return': <class 'float'>}