FastAPI 类型提示

FastAPI 类型提示

FastAPI广泛使用了Python 3.5版本以上的 类型 提示功能。事实上,Python是一种动态类型的语言。这也恰好是Python的独特功能。在Python代码中,一个变量不需要被声明为属于某种类型,它的类型是由分配给它的瞬时值动态决定的。Python的解释器不进行类型检查,因此很容易出现运行时异常。

在下面的例子中,定义了一个带有两个参数的 除法() 函数,并返回它们的除数,假设参数将是数字。

>>> def division(a, b):
   return a/b
>>> division(10, 4)
2.5
>>> division(10, 2.5)
4.0

然而,如果传递给函数的其中一个值恰好是非数字的,就会导致TypeError,如下所示。

>>> division("Python",5)
TypeError: unsupported operand type(s) for /: 'str' and 'int'

即使是像IDLE这样的基本编码环境,也会指出该函数需要两个参数,但不会指定其类型,因为它们还没有被声明。

FastAPI - 类型提示

Python 新的类型提示功能有助于向用户提示要传递的参数的预期类型。这可以通过在参数后面添加冒号和数据类型来实现。我们将重新定义 division() 函数,如下所示

FastAPI - 类型提示

注意,在调用函数时,Python提示了每个要传递的参数的预期类型。然而,这并不能阻止在传递不兼容的值时出现 TypeError。你必须使用一个静态类型检查器,如 MyPy ,在运行前检查兼容性。

正如函数定义中的形式参数一样,可以为函数的返回值提供类型提示。就在函数定义语句中的冒号之前(在该函数块开始之后)添加一个箭头(->)和类型。

FastAPI - 类型提示

然而,如前所述,如果不兼容的值被传递给函数,或者被函数返回,Python 会报告 TypeError。使用MyPy静态类型检查器可以发现这样的错误。首先安装mypy软件包。

pip3 install mypy

将以下代码保存为tynecheck.py

def division(x:int, y:int) -> int:
   return (x//y)
a=division(10,2)
print (a)
b=division(5,2.5)
print (b)
c=division("Hello",10)
print (c)

使用mypy检查这段代码是否有类型错误。

C:\python37>mypy typechk.py
typechk.py:7: error: Argument 2 to "division" has incompatible
type "float"; expected "int"
typechk.py:10: error: Argument 1 to "division" has
incompatible type "str"; expected "int"
Found 2 errors in 1 file (checked 1 source file)

在对函数的第二次和第三次调用中存在错误。在第二次调用中,传递给 y 的值是 float ,而预期是 int 。在第三次调用中,传给 x 的值是 str ,而预期是 int 。(注意//运算符返回整数除法)。

所有的标准数据类型都可以作为类型提示使用。这可以通过全局变量、作为函数参数的变量、函数定义内的变量等来实现。

x: int = 3
y: float = 3.14
nm: str = 'abc'
married: bool = False
names: list = ['a', 'b', 'c']
marks: tuple = (10, 20, 30)
marklist: dict = {'a': 10, 'b': 20, 'c': 30}

在较新版本的Python(3.5版以上)标准库中,新增加的一个模块是类型化模块。它为相应的标准集合类型定义了特殊类型。类型化模块中的类型有 List, Tuple, Dict, 和 Sequence 。 它还包括 UnionOptional 类型。注意,数据类型的标准名称都是小写的,而打字模块中的数据类型的第一个字母是大写的。利用这一特性,我们可以询问一个特定类型的集合。

from typing import List, Tuple, Dict
# following line declares a List object of strings.
# If violated, mypy shows error
cities: List[str] = ['Mumbai', 'Delhi', 'Chennai']
# This is Tuple with three elements respectively
# of str, int and float type)
employee: Tuple[str, int, float] = ('Ravi', 25, 35000)
# Similarly in the following Dict, the object key should be str
# and value should be of int type, failing which
# static type checker throws error
marklist: Dict[str, int] = {'Ravi': 61, 'Anil': 72}

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程