# 10 · 类型注解与 mypy

> 学完这章，你能给真实项目补注解、读懂 `mypy --strict` 的输出，并清楚地区分「静态检查」与「运行时校验」。

## 本章目标

- [ ] 能解释注解只是 `__annotations__` 里的对象，运行时不检查也不转换
- [ ] 能写出 `list[int]`、`int | None`、`Callable[[int], str]` 等现代写法，并知道 `Optional` 只是历史拼写
- [ ] 能说明 `Any`、`object`、未注解三者的检查差异，知道 `Any` 会沿调用链扩散
- [ ] 能用 `TypedDict` 描述 JSON、用 `cast`/`reveal_type`/`type: ignore[code]` 处理边界
- [ ] 能读懂 `mypy --strict` 的常见错误码，并知道 strict 下「不写注解」也是错误
- [ ] 能在边界处用 `isinstance`/`TypeGuard` 做运行时校验，不把类型检查当校验

## 前置知识

- 第 02 章（函数签名、默认参数）、第 06 章（参数模型）、第 08 章（类与属性）
- 任意静态语言（C/C++/Go/Java）的类型系统经验

## 从你熟悉的语言出发

| 概念 | C / C++ | Go | Java | Python |
| --- | --- | --- | --- | --- |
| 类型检查时机 | 编译期（C++ 有 RTTI） | 编译期 | 编译期 + 运行期反射 | 运行时不检查，交给 mypy/pyright |
| 注解语法 | 声明符 `int x` | `var x int` | `int x` | `x: int`，函数 `-> int` |
| 泛型 | 模板（单态化） | 1.18+ 类型参数 | 泛型擦除 | `list[int]`，运行时可取到对象 |
| 空值 | 指针/`nullptr` | `nil` | `null` + 注解 | `int \| None`，检查器跟踪 |
| 结构化类型 | 无（C++20 concept） | 隐式 interface | 无 | `Protocol`（第 11 章） |
| 类型与运行时 | 类型是编译期概念 | 类型是编译期概念 | 反射可见 | 注解是普通对象，可打印 |

**类比一：注解是写给检查器的便签，不是写给解释器的指令。** C 的 `int x` 决定内存布局和指令选择；Python 的 `x: int` 只在函数/类的 `__annotations__` 里留一条记录。解释器执行 `f("1", "2")` 时不会看注解，也不会把字符串转成整数。

**类比二：`Any` 像关掉这一路的告警，`object` 像保留告警但要求先证明。** 把值标成 `Any`，检查器对它的所有操作都不再报错；标成 `object`，除了 `isinstance`/`repr` 等少数操作，其余都要先收窄。前者方便但危险，后者啰嗦但安全。

## 正文

### 10.1 注解是对象

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

`add.__annotations__` 是普通字典：

```pycon
>>> add.__annotations__
{'a': <class 'int'>, 'b': <class 'int'>, 'return': <class 'int'>}
```

`int` 是类对象，`list[int]` 是 `types.GenericAlias`，`int | None` 是 `types.UnionType`。它们能被打印、比较、放进容器，也能在运行时被读取。注解**不参与**参数绑定、不参与返回值转换，更不会在调用时抛 `TypeError`。

这也解释了为什么下面能正常运行：

```pycon
>>> from typing import cast
>>> add(cast(int, "1"), cast(int, "2"))
'12'
```

`cast(int, "1")` 在运行时原样返回 `"1"`，只是让 mypy 相信它是 `int`；`+` 于是做了字符串拼接。注解没有骗人，是 `cast` 在骗检查器。

### 10.2 现代写法：PEP 585 与 PEP 604

| 旧写法 | 现代写法 | 说明 |
| --- | --- | --- |
| `List[int]` | `list[int]` | PEP 585，内置容器可直接下标 |
| `Dict[str, int]` | `dict[str, int]` | 同上 |
| `Optional[int]` | `int \| None` | PEP 604，`types.UnionType` |
| `Union[int, str]` | `int \| str` | 同上 |
| `Callable[[int], str]` | 同左 | 仍需从 `collections.abc`/`typing` 导入 |

`Optional[T]` 不是「可选参数」，而是「`T` 或 `None`」。参数有默认值不等于可传 `None`：

```python
def greet(name: str = "world") -> str:  # 不能传 None
    return f"hello {name}"
```

要允许 `None` 必须写 `name: str | None = None`。

`from __future__ import annotations` 会把注解字符串化，运行时 `__annotations__` 里是字符串；Python 3.14 起默认延迟求值（PEP 649），不再需要该 future。字符串化的好处是避免在定义时求值昂贵/前向引用的类型，代价是运行时拿不到真实对象。

### 10.3 `Any`、`object` 与未注解

| 写法 | 检查器行为 | 运行时 | 建议 |
| --- | --- | --- | --- |
| `x: int` | 完整检查 | 无影响 | 默认选择 |
| `x: object` | 只能做所有对象都有的操作 | 无影响 | 需要「任意对象」但想保留检查 |
| `x: Any` | 关闭检查，并传染给结果 | 无影响 | 仅限边界，尽快收窄 |
| 不写注解 | strict 下报 `no-untyped-def`；默认模式下函数体仍可能不查 | 无影响 | 库代码避免 |

`Any` 的传染性：

```python
def leak() -> Any:
    return "text"


value: int = leak()  # mypy 不报
value + 1  # 运行时 TypeError
```

`Any` 进入容器后会污染元素类型：`list[Any]` 的元素可以赋给任何变量；函数返回 `Any` 会让调用方的检查失效。能在边界用 `object` + `isinstance` 就用 `object`；必须用 `Any` 时，在读入后立刻 `cast` 或校验成具体类型。

未注解在默认模式下不是完全不管：`check_untyped_defs = true` 仍会检查函数体，但参数/返回值是隐式 `Any`。strict 则要求所有函数（含嵌套函数）都有完整注解。

### 10.4 `TypedDict` 描述 JSON

```python
class User(TypedDict):
    name: str
    age: int
```

`TypedDict` 在运行时就是 `dict`，构造时不校验；它的价值是让检查器知道键和值的类型。`json.loads` 返回 `Any`，所以常见写法是：

```python
data = json.loads(text)
user = cast(User, data)
```

`cast` 不做任何检查，坏 JSON 也会「成功」。真正的外部输入必须在边界校验：

```python
if not isinstance(raw, dict):
    raise TypeError("not an object")
name = raw.get("name")
age = raw.get("age")
if not isinstance(name, str) or not isinstance(age, int):
    raise TypeError("bad shape")
```

`total=False` 可以让键可选；`NotRequired`/`Required` 可以逐键控制。注意 `bool` 是 `int` 的子类，端口/计数这类字段要显式排除 `True`/`False`。

### 10.5 `cast`、`reveal_type` 与 `type: ignore`

- `cast(T, value)`：告诉检查器「按 `T` 处理」，运行时原样返回。只在确实知道更多信息时用，且尽量靠近边界。
- `reveal_type(x)`：让 mypy 打印 `x` 的推断类型（`note`，不是错误）。3.11+ 的 `typing.reveal_type` 在运行时会向 stderr 打印类型；想避免运行期输出，可以用 `if TYPE_CHECKING:` 包住调用。
- `# type: ignore[code]`：抑制一条错误，必须带错误码并在同一行写原因。`warn_unused_ignores` 会把「多余的 ignore」也报出来，防止清理后残留。

```python
value = cast(int, raw)  # raw 已经过 isinstance 校验
```

不要用 `cast` 替代校验：`cast` 是单向的承诺，运行时不会兑现。

### 10.6 `mypy --strict` 的旗标

`--strict` 是一组开关的集合，常用的有：

| 旗标 | 含义 |
| --- | --- |
| `disallow_untyped_defs` | 每个函数都必须有注解 |
| `disallow_incomplete_defs` | 有注解的函数不能缺参数/返回注解 |
| `disallow_any_generics` | `list` 必须写 `list[int]` |
| `warn_return_any` | 返回 `Any` 时报错 |
| `warn_unused_ignores` | 多余的 `type: ignore` 报错 |
| `strict_equality` | 明显不可比较的类型判等报错 |
| `no_implicit_optional` | 默认 `None` 必须显式写 `| None` |

strict 下「不写注解」本身就是错误，这是它和默认模式最大的差别。团队落地时通常分两步：先对公共 API/核心模块开 strict，再逐步扩大；不要一次性给整个遗留项目开 strict 后靠 `ignore` 续命。

### 10.7 类型检查不能替代运行时校验

类型检查发生在开发期，输入来自网络/文件/命令行/环境变量时，检查器看不到真实数据。边界处必须校验：

```python
def is_str_list(values: object) -> TypeGuard[list[str]]:
    return isinstance(values, list) and all(isinstance(item, str) for item in values)


def first_upper(values: object) -> str:
    if not is_str_list(values):
        raise TypeError("values must be list[str]")
    return values[0].upper() if values else ""
```

`TypeGuard[T]` 只在「返回真」的分支把参数收窄为 `T`；返回假的分支不会收窄（3.13 的 `TypeIs` 会做否定收窄，第 11 章）。`runtime_checkable` 的 `Protocol` 只检查方法名，不检查签名，也不能替代字段级校验。

### 10.8 注解的求值时机

不带 future 时，注解在 `def`/`class` 执行时求值：

```python
def f(x: list[int]) -> None: ...
```

`list[int]` 会当场构造 `GenericAlias`。这带来两个后果：

- 前向引用需要字符串：`def f(x: "Node") -> None`，或启用 `from __future__ import annotations`。
- 昂贵/有副作用的注解表达式会在导入时执行；库代码应避免在注解里做重计算。

3.14 起 PEP 649 默认延迟求值，`__annotations__` 在首次访问时才算；这让前向引用和启动成本都更友好，但依赖「注解是对象」的元编程要改用 `annotationlib`。本章示例仍以 3.12 为基线，跨版本行为写在注释里。

## 报错现场

真实 `mypy --strict` 输出（mypy 2.4.1，文件见 `examples/10-type-annotations-mypy/02-mypy-catches/`）：

```text
before.py:4: error: Function is missing a type annotation  [no-untyped-def]
before.py:12: error: Incompatible types in assignment (expression has type "str", variable has type "int")  [assignment]
Found 2 errors in 1 file (checked 1 source file)
```

逐行读：

- `before.py:4`：`total(values)` 没有参数/返回注解；strict 下这是错误，错误码 `no-untyped-def`。
- `before.py:12`：`value: int = text`，右侧是 `str`；错误码 `assignment`。
- `Found 2 errors`：mypy 默认继续检查，不因第一个错误停止。

同一段代码在 CPython 下能跑：

```pycon
>>> def parse(text: str) -> int:
...     value: int = text
...     return value
>>> parse("42")
'42'
```

返回值是字符串 `'42'`，不是整数 `42`。这正说明注解不改变运行时；错误要等后续 `value + 1` 才爆。

修复后：

```text
Success: no issues found in 1 source file
```

## 反直觉差异：注解不影响运行，但 `Any` 会关闭检查

**你的直觉**：写了 `x: int`，运行时传字符串应该报错；`Any` 只是「任意类型」，应该和 `object` 差不多，甚至更严格。

**实际行为**：

1. 注解完全不参与运行。`add(cast(int, "1"), cast(int, "2"))` 返回 `'12'`，没有 `TypeError`。
2. `Any` 不是「更宽的类型」，而是「让检查器闭嘴」。`value: int = leak()`（`leak() -> Any`）不会报错；同样的值标成 `object` 就必须先 `isinstance`。
3. strict 下「不写注解」不是「不做检查」，而是直接报 `no-untyped-def`。

**为什么这样设计**：Python 要保持动态语言的运行时语义，注解只能是可选的元数据；把检查交给独立的静态工具，才能让同一份代码在无 mypy 的环境照常运行。`Any` 的设计目标是「渐进类型」——让未注解的代码也能被检查器接受，代价是它必须放弃这部分检查。

**正确写法**：

- 公共 API 写完整注解；内部临时脚本可以不写，但不要进库。
- 外部数据在边界校验后再 `cast` 成具体类型，不要一路 `Any`。
- 需要「任意对象」时用 `object`；确实要关闭检查时用 `Any`，并把它限制在最小范围。
- 不用 `cast` 掩盖类型错误；`cast` 是承诺，不是转换。

## 性能与复杂度

| 操作 | 实测（3.12.9 / macOS arm64） | 说明 |
| --- | --- | --- |
| 定义 1 个无注解函数（含编译） | 6.63 µs | `exec` 源码 |
| 定义 1 个带注解函数（含编译） | 8.61 µs | 多出注解求值 |
| 定义 200 个无注解函数 | 0.89 ms | 批量对比 |
| 定义 200 个带注解函数 | 1.32 ms | 约 +0.43 ms |
| 200 个函数仅 `exec`（已编译，注解求值） | 0.015 ms | 去掉编译后的净成本 |
| 200 个函数仅 `exec`（`from __future__` 字符串化） | 0.011 ms | 省去类型对象构造 |
| `mypy --strict` 冷缓存 | 约 1.2 s | 单目录、首次运行 |
| `mypy --strict` 热缓存 | 约 0.09 s | 增量缓存命中 |

注解的运行时成本主要在「定义函数时求值类型对象」，量级是微秒；真正的成本在类型检查器（秒级冷启动、毫秒级增量）。对启动敏感的 CLI，可以用 `from __future__ import annotations` 避免导入时构造复杂类型；对长期运行的服务，这点差异可以忽略。

## 示例索引

| 目录 | 演示什么 | 预期看到 |
| --- | --- | --- |
| `examples/10-type-annotations-mypy/01-annotations-are-metadata/` | 注解是对象、运行时不检查 | `runtime result: '12'`、`GenericAlias` |
| `examples/10-type-annotations-mypy/02-mypy-catches/` | strict 前后真实 mypy 输出 | `[no-untyped-def]`、`[assignment]`、`Success` |
| `examples/10-type-annotations-mypy/03-typeddict-json/` | TypedDict + JSON + 校验 | `cast bad` 仍成功、`validate` 拒绝 |
| `examples/10-type-annotations-mypy/04-any-vs-object/` | `Any` 传染 vs `object` 收窄 | 赋值通过、运行时 `TypeError` |
| `examples/10-type-annotations-mypy/05-reveal-type/` | `reveal_type` 的 mypy note | `Revealed type is "int"` |
| `examples/10-type-annotations-mypy/06-runtime-validation/` | `TypeGuard` 与边界校验 | `True/False`、三种 `rejected` |

## 练习题

1. 实现 `clamp(value, low, high) -> int`，越界夹取，`low > high` 抛 `ValueError`。见 `exercises/10/01-clamp/`。
2. 定义 `ServerConfig(TypedDict)`，实现 `load_config(raw: object)`，校验 `host: str`、`port: int`（排除 `bool`）。见 `exercises/10/02-typeddict-config/`。
3. 实现 `is_int(value: object) -> TypeGuard[int]` 与 `as_int(value: object) -> int`。见 `exercises/10/03-narrow-object/`。
4. 用 `Literal`/`Final` 定义 `Mode` 与 `DEFAULT_MODE`，实现 `format_mode(mode: str)`。见 `exercises/10/04-literal-mode/`。

<details><summary>参考答案</summary>

1. 先比较 `low > high` 抛错，再依次处理小于下界、大于上界、区间内三种情况。
2. 先 `isinstance(raw, Mapping)`，再逐字段 `isinstance`；`port` 用 `isinstance(port, bool)` 单独排除。
3. `is_int` 返回 `isinstance(value, int) and not isinstance(value, bool)`；`as_int` 在 `if is_int(value)` 分支直接返回。
4. `Mode = Literal["dev", "prod"]`；`DEFAULT_MODE: Final[Mode] = "dev"`；运行时仍要检查 `mode in ALLOWED`。

</details>

## 章末自检

1. 注解存在哪里？运行时会检查吗？
2. `list[int]` 与 `List[int]` 的区别？`int | None` 与 `Optional[int]` 呢？
3. `Any`、`object`、未注解三者在检查器眼里有什么不同？
4. `cast` 和 `isinstance` 各自解决什么问题？能互相替代吗？
5. `TypedDict` 是运行时校验吗？`json.loads` 之后为什么要校验？
6. strict 下「不写注解」会怎样？`--strict` 包含哪些常用旗标？
7. `TypeGuard` 与 3.13 的 `TypeIs` 在否定分支上有什么差别？
8. `from __future__ import annotations` 改变了什么？3.14 的默认行为是什么？

<details><summary>答案要点</summary>

1. 存在函数/类的 `__annotations__` 字典里；运行时不检查、不转换。
2. 现代写法是内置容器下标与 `|`；`Optional[T]` 只是 `T | None` 的历史拼写。
3. `Any` 关闭检查并传染；`object` 保留检查但需收窄；未注解在 strict 下报 `no-untyped-def`。
4. `cast` 只影响静态检查、运行时原样返回；`isinstance` 才是运行时判断。不能互相替代。
5. 不是；`TypedDict` 运行时就是 `dict`。`json.loads` 返回 `Any`，坏形状必须显式校验。
6. 直接报 `no-untyped-def`；还包括 `disallow_any_generics`、`warn_return_any`、`warn_unused_ignores`、`strict_equality` 等。
7. `TypeGuard` 只收窄为真的分支；`TypeIs` 在假分支收窄为排除后的类型。
8. 把注解字符串化、延迟求值；3.14 起默认延迟求值（PEP 649）。

</details>

## 延伸阅读

- The Python Tutorial §5.5 *Type hints*（`typing` 模块）
- The Python Standard Library §7.8 *`typing`*（`TypedDict`、`Literal`、`Final`、`TypeGuard`、`reveal_type`）
- mypy 文档：*Type hints cheat sheet*、*Command line*（`--strict`）、*Common issues*
- PEP 484 *Type Hints*
- PEP 585 *Type Hinting Generics In Standard Collections*
- PEP 604 *Allow writing union types as `X | Y`*
- PEP 589 *TypedDict*
- PEP 647 *User-Defined Type Guards*
- PEP 649 *Deferred Evaluation Of Annotations Using Descriptors*
