栈记
PythonPython 进阶教程

类型注解

* / ** 的特殊用法,以及基本类型、函数类型、TypedDict、Protocol、泛型与 Annotated

语法中 * 和 ** 的特殊操作

注意:这跟类型没有任何关系

在函数中 *args 和 **kwargs 对应函数中不定长参数两种方式的接收,分别对应元组和字典类型。

def func(*args, **kwargs):
    print(args)  # 元组 (1, 2, 3)
    print(kwargs)  # 字典 {'a': 4, 'b': 5}

func(1, 2, 3, a=4, b=5)

还有一种方案, 直接使用 * 接收参数,这种方式表示关键字参数的分隔符,本身没有意义,从它之后就只能接收关键字参数。

在接收多个参数的时候强制使用关键字参数,提高方法调用的可读性。

def func(a, b, *, c, d):
    print(a)  # 1
    print(b)  # 2
    print(c)  # 3
    print(d)  # 4

# 3 和 4 必须以关键字参数的方式传入
func(1, 2, c=3, d=4)

当不接收参数时,可以作为解包操作符使用,同样对应简单类型的可迭代对象和字典类型。

def func(a, b, c):
    print(a)  # 1
    print(b)  # 2
    print(c)  # 3

args = (1, 2, 3)
kwargs = {'a': 1, 'b': 2, 'c': 3}

func(*args)  # 解包元组
func(**kwargs)  # 解包字典

不定长参数的解构取值也可以使用 *; 对于字典来说取的是 key, 如果解构变量的个数不足以接收所有的参数且没有使用 *, 则会抛出 ValueError。

args = [1, 2, 3, 4, 5]
a, b, *rest = args
print(rest)  # [3, 4, 5]

kwargs = {'a': 1, 'b': 2, 'c': 3, 'd': 4}
a, b, *rest = kwargs
print(rest)  # ['c', 'd']

基本类型

可以直接使用内置类型直接作为类型注解;

name: str = 'zs'
age: int = 18
height: float = 1.75
is_student: bool = True
data: bytes = b'hello'

结构数据类型,3.8 之前需要导入 from typing import List, Dict, Tuple, Set, 之后也可以直接使用内置类型。

names: list[str] = ['zs', 'ls', 'ww']
ages: dict[str, int] = {'zs': 18, 'ls': 19, 'ww': 20}
points: tuple[int, int] = (1, 2)
unique_ids: set[int] = {1, 2, 3}

可选类型(联合类型) Optional 之前需要导入 from typing import Optional, 3.10 之后可以直接使用 | None 来表示可选类型。

name: str | None = None # 字符串或者 None
names: list[str | None] = ['zs', 'ls', None] # 字符串或者 None 的列表

value: int | str = 42 # 整数或者字符串

Any 表示任意类型,使用 from typing import Any 导入。

from typing import Any

data: Any = 'hello'  # 可以是任何类型

函数类型

def add(a: int, b: int) -> int:
    return a + b

可以使用 Callable 声明一个函数类型

from typing import Callable

# 第一个是函数的参数,第二个是函数的返回值
def apply(func: Callable[[int, int], int]) -> int:
    return func(1, 2)

类型别名

可以通过复杂或者通用的类型定义类型别名,达到复用和提高可读性的目的。

from typing import TypeAlias

UserDict: TypeAlias = dict[str, str]

def get_user_info() -> UserDict:
    return {'name': 'zs', 'email': ''}

复杂数据类型 Listral

开始定义的列表都是 arr: list[str]; 不够精确,可以通过 Literal 来定义一个具体的值或者一组值。

from typing import Literal

arr: Literal['active', 'inactive'] = 'active'  # 只能是 'active' 或 'inactive'

复杂数据类型 TypedDict

用来描述字典中每个键的数据类型

from typing import TypedDict

class User(TypedDict):
    name: str
    age: int
    height: float | None  # height 可以是 float 或 None

user: User = { 'name': 'zs', 'age': 18, 'height': 1.75 }

如果需要整个字典都是可选的,可以使用 total=False 来定义一个可选的 TypedDict。

# 可以通过 Required 和 NotRequired 来控制每个字段是否必选
from typing import TypedDict, Required, NotRequired

class User(TypedDict, total=False):
    name: Required[str]
    age: NotRequired[int]
    height: float

user: User = {}

复杂数据类型 Protocol

定义一个协议,任何使用此协议的方法或者类都要满足该类型,优先类似于 ts interface | abstract 的定义。

from typing import Protocol

class SupportsClose(Protocol):
    is_closed: bool

    def close(self) -> None: ...

# 不用继承 SupportClose
class Resource:
    def __init__(self) -> None:
        self.is_closed = False

    def close(self) -> None:
        self.is_closed = True

def close_resource(resource: SupportsClose) -> None:
    resource.close()
    print(f"Resource closed: {resource.is_closed}")

if __name__ == "__main__":
    res = Resource()
    close_resource(res)

复杂数据类型泛型

需要调用时再传入的类型就是泛型,换句话说就是在定义的时候不确定的类型;

使用 TypeVar 定义泛型变量

from typing import TypeVar

T = TypeVar('T')

def identity(x: T) -> T:
    return x

泛型约束

from typing import TypeVar

T = TypeVar('T', int, float) # 通过传递类型来约束泛型的范围

# 通过 bound 约束泛型必须是某个类型的子类型
class Animal: pass
class Dog(Animal): pass

AnimalType = TypeVar('AnimalType', bound=Animal)

def speak(animal: AnimalType) -> AnimalType:
    return animal

speak(Dog())  # 返回 Dog
speak(object())  # 错误: object 不是 Animal 子类

泛型类

通过 Generic 定义一个泛型类, 需要传入一个或者多个类型变量。

from typing import Generic, TypeVar

T = TypeVar('T')
V = TypeVar('V')

class User(Generic[T, V]):
    def __init__(self, name: V, money: T) -> None:
        self.name = name
        self.money = money

    def get_money(self) -> T:
        return self.money

user = User[str, int]('zs', 20000000)

Annotated 附加元数据

FastAPI 比较火的情况下这个类型很有必要深入一下

Annotated[T, metadata1, metadata2, ...] 给类型 T 添加一些元数据, 这些元数据可以是任何类型的值。

from typing import Annotated, get_type_hints

class Config:
    env: Annotated[str, '环境变量']
    get_env: Annotated[callable, '获取环境变量的函数']

print(get_type_hints(Config, include_extras=True))
# {'env': typing.Annotated[str, '环境变量'], 'get_env': typing.Annotated[<built-in function callable>, '获取环境变量的函数']}

在 FastAPI 中, Annotated 用于给请求参数添加额外的验证和描述信息以及依赖注入。

from fastapi import FastAPI, Query
from typing import Annotated

app = FastAPI()

@app.get("/items/")
def get_items(
    skip: Annotated[int, Query(default=0, ge=0, le=100), description="跳过的记录数"],
    limit: Annotated[int, Query(default=10, ge=1, le=100), description="返回的记录数"],
    query: Annotated[str | None, Query(default=None, max_length=50), description="查询字符串"]
) -> dict[str, str | int]:
    pass

On this page