Python 类型注解实战:让 mypy 帮你抓 bug

为什么需要类型注解

Python 是动态类型语言,变量类型在运行时才确定,这带来了灵活,也带来了隐患:很多错误只有在代码真正跑起来、走到那条分支时才会暴露。类型注解(type hints)本身不改变程序运行行为,但配合静态类型检查器 mypy,可以在不动代码的情况下提前发现类型不匹配、参数传错、返回值类型不符等问题。

本文用的都是 Python 3.8+ 标准库里真实存在的语法和 typing 模块里的真实类型,mypy 的调用方式以官方文档为准。

基础注解与基本类型

函数参数和返回值都可以加注解,语法是 参数: 类型 和 -> 返回类型:

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

def greet(name: str) -> str:
    return "hello " + name

x: float = 3.14

mypy 检查时会发现这类错误:

add("1", 2)        # 错误:参数 1 应为 int
greet(123)         # 错误:参数应为 str

注意注解只是提示,运行时 add("1", 2) 仍能执行(字符串和数字不能相加会抛 TypeError,但这是运行时行为,注解不拦截)。真正拦截错误的是 mypy 的静态分析。

容器与 typing 模块

列表、字典这类容器需要标注元素类型,用 typing 里的 List、Dict、Tuple、Set:

from typing import List, Dict, Tuple

def total(prices: List[float]) -> float:
    return sum(prices)

def build() -> Dict[str, int]:
    return {"a": 1, "b": 2}

def first(item: Tuple[int, str]) -> int:
    return item[0]

Python 3.9 起内置的 list、dict、tuple 也支持泛型写法(list[float]),但 typing 写法在 3.8 仍然兼容,跨版本更稳。

Optional 与 Union

一个值可能是某种类型,也可能是 None,用 Optional[T],它等价于 Union[T, None]:

from typing import Optional

def find_user(uid: int) -> Optional[str]:
    users = {1: "alice"}
    return users.get(uid)   # 找不到时返回 None

如果返回类型写成 str 但函数可能返回 None,mypy 会报不兼容。

多个可能类型用 Union:

from typing import Union

def parse(value: str) -> Union[int, float]:
    if "." in value:
        return float(value)
    return int(value)

自定义类与 TypeVar

给函数加上泛型约束,用 TypeVar:

from typing import TypeVar, Sequence

T = TypeVar("T")

def head(items: Sequence[T]) -> T:
    return items[0]

Sequence 是 typing 里的抽象类型,比 list 更宽松——tuple、str 都满足 Sequence,便于写出更通用的函数。

实际跑一遍 mypy

先安装:pip install mypy

把下面这段有问题的代码存成 demo.py:

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

add("x", 2)

运行检查:

mypy demo.py

输出类似:

demo.py:4: error: Argument 1 to "add" has incompatible type "str"; expected "int"
Found 1 error in 1 file (checked 1 source file)

想在整个项目里检查,直接对目录运行:

mypy src/

常用开关:--strict 开启全部严格检查;--ignore-missing-imports 跳过第三方库缺失的桩文件;--disallow-untyped-defs 要求所有函数都有注解。

小结

  • 类型注解是写给人(和工具)看的提示,运行时不强制,但 mypy 能据此在提交前抓出一大类低级错误。
  • 基础类型直接写 int/str/float,容器用 typing 的 List/Dict/Tuple,兼容性最好。
  • Optional[T] 表达「可能为空」,Union 表达「多类型之一」,别用 str 隐式兜底。
  • TypeVar + Sequence 能让函数在不损失类型安全的前提下更通用。
  • 养成习惯:写完模块跑一次 mypy,比等到线上报错便宜得多。
posted @ 2026-11-13 08:42  徽音说AI搜索  阅读(0)  评论(0)    收藏  举报