黄同学的后端和 Agent 笔记开通
Hello 后端

常用的类型写法

黄同学约 5 分钟读完免费

前置知识

类型提示是什么:参数、返回值、变量后面可以写类型;Python 不检查,mypy 和编辑器检查。

一句话总结

这一篇是一张速查表:装东西的 list[int]、可能没有的 int | None、只能是几个值之一的 Literal,再加上读库的代码时会碰到的 Annotated、Callable。同一个意思有新老两种写法的,本站用新的,老的认得就行。

让 AI 给几个函数加类型提示,你可能会看到同一个意思有三种写法:

python
def find_coupon(code: Optional[str]) -> ...
def find_coupon(code: Union[str, None]) -> ...
def find_coupon(code: str | None) -> ...

List[str] 和 list[str] 也混着用,到底哪个是现在的写法?下面按「AI 代码里最常见」的顺序一种一种看,例子都是订单服务里的函数签名,函数体省掉了。

装东西的

列表、字典这些装东西的类型,方括号里写装的是什么:

python
def order_ids(user_id: int) -> list[int]: ...              # 一列整数
def stock_of(product_ids: list[int]) -> dict[int, int]: ... # 键是商品 id,值是库存
def first_order(user_id: int) -> tuple[int, str]: ...       # 一组:订单 id 和状态
def tags_of(product_id: int) -> set[str]: ...               # 一组不重复的字符串
  • list[int]:列表,里面每一项都是 int。
  • dict[int, int]:字典,先写键的类型,再写值的类型。
  • tuple[int, str]:元组,每个位置各写一个类型,个数是固定的。
  • set[str]:集合(set),里面每一项都是 str。

可能没有的

查一个订单,可能查不到,返回 None。这种「是 X,或者是 None」的类型写成 X | None:

python
def get_order(order_id: int) -> Order | None: ...
def apply_coupon(amount: int, coupon: str | None = None) -> int: ...

竖线 | 读作「或」,int | str 就是「整数或字符串」。

老写法是从 typing 里导入两个名字:Optional[str] 等于 str | None,Union[int, str] 等于 int | str。Optional 这个词就是「可以没有」的意思,在 AI 代码和老项目里非常多,看到了换成竖线的写法去理解就行。

注意

参数的默认值是 None,类型就要写 | None。写成 coupon: str = None,mypy 会报 Incompatible default for parameter "coupon"。以前的 mypy 会自动把它当成 str | None,现在不会了,AI 照旧资料常这样写。

只能是这几个值

订单状态只有三种,可是写成 str 的话,传个 "DONE" 进来也没人管。这时用 Literal 把能用的值一个个列出来:

python
from typing import Literal

type Status = Literal["UNPAID", "PAID", "CANCELLED"]

def find_orders(user_id: int, status: Status | None = None) -> list[int]: ...

find_orders(1, status="DONE")
text
app/orders.py:7: error: Argument "status" to "find_orders" has incompatible type "Literal['DONE']"; expected "Literal['UNPAID', 'PAID', 'CANCELLED'] | None"  [arg-type]

第 3 行的 type Status = ... 是给一个长类型起个名字,后面写 Status 就行。type OrderId = int 也是这样,名字比 int 多说了一句「这个整数是订单 id」。

和它相反的是 Any:什么都行,mypy 不检查。Any 用多了,等于没写类型。

函数当参数

函数也是对象,能当参数传。它的类型写成 Callable[[参数类型...], 返回值类型]:

python
from collections.abc import Callable

def retry(func: Callable[[], int], times: int = 3) -> int: ...

Callable[[], int] 是「不要参数、返回 int 的函数」。Callable 从 collections.abc 导入,从 typing 导入也行,那是老地方。

读库的签名时会碰到的

下面几种,自己写代码时用得少,读 FastAPI、Pydantic 的代码时常碰到,认得就行:

  • Annotated:在类型后面附一条说明。Annotated[int, Field(gt=0)] 还是 int,只是附了一条「要大于 0」。附的东西 Python 和 mypy 都不管,给读它的库看。Pydantic 校验数据和依赖注入会用到。
  • list[T] 里的 T:泛型。T 是一个占位的类型,用的时候才定下来。def first[T](items: list[T]) -> T 的意思是「传进来一列什么,就返回一个什么」。
  • Protocol:写下「要有哪些方法」。只要一个对象有这些方法,就算符合,不用继承谁。这正是继承和多态里讲的鸭子类型,只是写成了 mypy 能检查的样子。
  • TypedDict:给一个字典规定「有哪几个键、各是什么类型」。要检查外面来的 JSON,本站用 Pydantic,不用它。

新老写法对照

意思 老写法 新写法 新写法从哪个版本起
一列整数 typing.List[int] list[int] Python 3.9
字典 typing.Dict[str, int] dict[str, int] Python 3.9
可能是 None Optional[int] int | None Python 3.10
几种之一 Union[int, str] int | str Python 3.10
给类型起名字 OrderId: TypeAlias = int type OrderId = int Python 3.12
泛型 T = TypeVar("T") def firstT Python 3.12

本站按 Python 3.14 写,一律用新写法。

版本提醒

typing.List、typing.Dict 这些已经是弃用的别名,还能跑,只是官方不再推荐。AI 照旧资料写,常在文件开头 from typing import List, Dict, Optional;看到了知道是老写法就行,改不改都不影响运行。


下一篇:Pydantic 校验数据