FastAPI - 类型提示



FastAPI 广泛使用了 Python 3.5 及更高版本提供的类型提示功能。事实上,Python 以动态类型语言而闻名,这也是 Python 的一个显著特征。在 Python 代码中,无需声明变量属于某种类型,其类型由动态赋予它的值决定。Python 解释器不执行类型检查,因此容易出现运行时异常。

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

>>> 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 Type Hint

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

FastAPI Type Hint

注意,在调用函数时,Python 会提示每个参数的预期类型。但是,如果传递了不兼容的值,这并不会阻止 TypeError 的出现。您必须使用静态类型检查器,例如MyPy,在运行之前检查兼容性。

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

FastAPI Type Hint

但是,如前所述,如果传递给函数的值不兼容,或者函数返回的值不兼容,Python 会报告 TypeError。使用 MyPy 静态类型检查器可以检测此类错误。请先安装 mypy 包。

pip3 install mypy

将以下代码保存为 typecheck.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 及更高版本)标准库中的一个新增内容是 typing 模块。它为相应的标准集合类型定义了特殊类型。typing 模块中的类型是List、Tuple、Dict 和 Sequence。它还包含UnionOptional类型。请注意,数据类型的标准名称都是小写,而 typing 模块中的名称首字母大写。使用此功能,我们可以要求一个特定类型的集合。

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}
广告