Python 类型注解(Type Hints)
用注解表达调用约定,区分解释器的真实行为和静态检查器给出的诊断。
学完这一章,你能够
- 用注解表达调用约定,区分解释器的真实行为和静态检查器给出的诊断。
注解写下接口的约定
类型注解把输入和返回值的约定写到接口上。函数参数写成 hub: str,返回值写在 -> 后。Python 3.6 起也可写变量注解,例如 retries: int = 2。一个名称可以后来绑定到不同类型的对象。注解本身不会把这个名称或对象锁定为某种类型。
比较同一个加法函数收到整数和字符串的结果。两个整数得到数值相加,两个字符串得到拼接,字符串和整数混加则由加法运算抛出 TypeError。写了 -> int 也不会自动转换返回值。要在运行时拒绝外部输入,应另外校验。
用 times: int = 1 可以同时表达预期类型与默认值。times 省略时取 1,显式传 0 时仍使用 0。str | None 表示值可以为 None,是否可以省略参数要看它有没有默认值。
把容器元素和不同输入讲清楚
list[int] 指定元素类型,dict[str, int] 分别指定键和值,set[str] 指定集合元素,tuple[int, str, bool] 按位置描述定长元组。Python 3.9 起内置容器支持这些写法。维护旧项目时仍可能看到 typing.List、Dict、Set 和 Tuple,现代项目通常可直接用内置类型。带参数的 list[int] 无法直接用作 isinstance 的第二个实参。
Optional[str] 等价于 Union[str, None],Python 3.10 起也可写 str | None。查编号时,命中返回字符串,缺失返回 None。接收文本、整数或整数列表时,可用 str | int | list[int],在函数体内再按实际值分支。识别 list 只能判断容器类型,若数据来自外部还需检查元素。
分别运行解释器和静态检查器
用解释器运行自编实例,可以观察注解存在时仍能把两个字符串拼接。另用同一个环境的 python -m mypy 文件名.py 做静态检查。如果尚未安装,可先在项目自己的环境中安装 Mypy,并固定版本以便团队复查。将本章正例与负例下载到同一目录,然后分别运行 python -m mypy python-type-hints-check-good.py 和 python -m mypy python-type-hints-check-bad.py。本站用 Mypy 1.18.2 检查时,正例通过,负例得到两条参数类型诊断和一条运单分钟数字段相加的诊断。
同一个参数不匹配的调用可能在解释器中得到字符串,在 Mypy 中得到参数诊断。诊断行号、格式和覆盖范围取决于工具版本与配置。编辑器的类型提示还取决于所选解释器、扩展和检查设置。它们可能提供补全和高亮。
注解可以在运行时被读取。CPython 3.12 通常在定义时求值函数注解。from __future__ import annotations 会把相应注解保留成字符串,读取工具可解析它们。Python 3.14 默认引入延迟求值。注解表达式和检查它们的代码可能带来开销或异常,不能一概保证零成本。仅对可信代码解析注解。
所需环境:Python 3.12 和 Mypy
当前源码 SHA256:699c18ac092992831aeb34c7991427500d0eaba5daa2f11e9fb03113213b425e
所需环境:Python 3.12 和 Mypy
当前源码 SHA256:983b79db4edc936b16918b53ca40fab1f628800b5c7776e138d9262f2fc5a541
先给公共接口和结构化数据加注解
可先为公共函数、复杂返回值和常被误用的数据结构加注解,再逐步扩展。简单常量往往能推断类型。团队可统一最低 Python 版本、写法与检查配置。第三方库可能自带注解,也可能提供独立的 .pyi 存根。先核对库与存根的版本,再考虑小范围包装器。Any 会放宽静态检查,不能作为运行时校验。
按字段处理运单时,dict[str, str | int] 只说明任意键的值可能是字符串或整数,无法表达 minutes 一定是整数。TypedDict 可以分别标注 hub 与 minutes。运单为空时返回 None,否则把分钟数求和除以条数。本例还核对缺键和错误字段会怎样影响实际执行。
常见写法与版本条件
| 写法 | 表达的约定 | 版本与运行边界 |
|---|---|---|
| label: str | 变量预计绑定字符串 | Python 3.6 起支持变量注解,未赋值不会产生可读的绑定 |
| times: int = 1 | 参数预计为整数,默认 1 | 省略和显式传值不同 |
| list[int] / set[str] | 容器元素类型 | 内置泛型从 Python 3.9 起可用,运行时不会自动逐项校验 |
| dict[str, int] | 键为字符串,值为整数 | 一般字典注解不能区分每个固定键的类型 |
| tuple[int, str, bool] | 三项分别标注类型 | 若需任意长度的整数元组,可写 tuple[int, ...] |
| str | None / Optional[str] | 值可以为 None | 管道语法从 Python 3.10 起可用。省略实参仍需默认值 |
| str | int | list[int] | 三种输入之一 | 分支处理还应关注列表元素的真实类型 |
| TypedDict | 按键定义字段类型 | 静态描述普通字典,运行时仍需检查外部数据 |
本章自编源码与运行范围
"""蓝色天空网 mbsky.com | Observe annotations and runtime behavior on owned values."""
import inspect
from pathlib import Path
import sys
from typing import Any, Dict, List, Optional, Set, Tuple, TypedDict, Union, get_args, get_origin, get_type_hints
sys.path.insert(0, str(Path(__file__).resolve().parent))
from mbsky_pychecks import Checks
hub: str = "dock"
retries: int = 2
enabled: bool = True
minutes: list[int] = [12, 20]
future_rate: int
def raw_notice(code, suffix):
return f"{code}-{suffix}"
def notice(code: str, suffix: str) -> str:
return f"{code}-{suffix}"
def combine(first: int, second: int) -> int:
return first + second
def repeat(label: str, times: int = 1) -> str:
return " ".join([label] * times)
def find_hub(label: str) -> str | None:
return {"dock": "A1"}.get(label)
def read_label(label: str | None) -> str:
return label if label is not None else "missing"
def describe(data: str | int | list[int]) -> None:
if isinstance(data, str):
print(f"text={data}")
elif type(data) is int:
print(f"integer={data}")
elif isinstance(data, list) and all(type(item) is int for item in data):
print(f"minutes={data}")
else:
raise TypeError("expected text, integer or list of integers")
class Delivery(TypedDict):
hub: str
minutes: int
def mean_minutes(deliveries: list[Delivery]) -> float | None:
if not deliveries:
return None
return sum(delivery["minutes"] for delivery in deliveries) / len(deliveries)
def statistics(values: list[float]) -> dict[str, float]:
return {"mean": sum(values) / len(values), "maximum": max(values)}
def main():
import contextlib
import io
checks = Checks()
checks.eq("annotated and plain functions agree on valid inputs",
(raw_notice("P7", "ready"), notice("P7", "ready")), ("P7-ready", "P7-ready"))
checks.eq("function parameter and return metadata",
{name: value.__name__ for name, value in get_type_hints(notice).items()},
{"code": "str", "suffix": "str", "return": "str"})
checks.eq("module annotated variables preserve values", (hub, retries, enabled, minutes),
("dock", 2, True, [12, 20]))
checks.eq("annotation without assignment records type", __annotations__["future_rate"] is int, True)
checks.eq("annotation alone creates no readable value", "future_rate" in globals(), False)
checks.eq("integer addition", combine(7, 8), 15)
wrong: Any = "7"
other: Any = "8"
checks.eq("wrong annotated arguments still concatenate", combine(wrong, other), "78")
checks.raises("mixed values fail at actual operator", TypeError, lambda: combine(wrong, 8))
checks.eq("annotation does not convert return value", type(combine(wrong, other)).__name__, "str")
checks.eq("repeat default explicit and zero", (repeat("dock"), repeat("dock", 3), repeat("dock", 0)),
("dock", "dock dock dock", ""))
checks.eq("optional hit and miss", (find_hub("dock"), find_hub("missing")), ("A1", None))
checks.eq("explicit None accepted", read_label(None), "missing")
checks.raises("nullable argument without default remains required", TypeError, lambda: read_label())
checks.eq("optional spelling equivalent to union", Optional[str] == Union[str, None] == (str | None), True)
pairs = ((List[int], list[int], (int,)),
(Dict[str, int], dict[str, int], (str, int)),
(Tuple[int, str, bool], tuple[int, str, bool], (int, str, bool)),
(Set[str], set[str], (str,)))
for legacy, modern, expected in pairs:
label = get_origin(modern).__name__
checks.eq(f"legacy and modern {label} origins", get_origin(legacy) is get_origin(modern), True)
checks.eq(f"legacy and modern {label} parameters",
get_args(legacy) == get_args(modern) == expected, True)
collection: list[int] = [18]
collection.append(wrong)
checks.eq("element annotation is not a runtime filter", collection, [18, "7"])
checks.raises("parameterized generic cannot be isinstance target", TypeError,
lambda: isinstance(collection, list[int]))
for value, line in (("dock", "text=dock"), (12, "integer=12"), ([12, 20], "minutes=[12, 20]")):
stream = io.StringIO()
with contextlib.redirect_stdout(stream):
result = describe(value)
checks.eq("union branch " + type(value).__name__, (stream.getvalue().strip(), result), (line, None))
checks.raises("list check needs item verification", TypeError, lambda: describe([wrong]))
checks.raises("explicit validation rejects boolean case", TypeError, lambda: describe(True))
checks.eq("TypedDict value is ordinary dict", type(Delivery(hub="A", minutes=12)) is dict, True)
checks.eq("structured average empty and populated",
(mean_minutes([]), mean_minutes([{"hub": "A", "minutes": 12}, {"hub": "B", "minutes": 20}])),
(None, 16.0))
missing_field: Any = [{"hub": "A"}]
invalid_field: Any = [{"hub": "B", "minutes": "slow"}]
checks.raises("missing field is runtime KeyError", KeyError, lambda: mean_minutes(missing_field))
checks.raises("invalid field fails actual addition", TypeError, lambda: mean_minutes(invalid_field))
checks.eq("annotated statistics on floats", statistics([2.0, 6.0]), {"mean": 4.0, "maximum": 6.0})
eager = {"hits": []}
exec("def mark():\n hits.append('evaluated')\n return int\ndef build(n: mark()):\n return n\n", eager)
checks.eq("3.12 default evaluates function annotation at definition", eager["hits"], ["evaluated"])
postponed = {}
exec("from __future__ import annotations\ndef build(n: int) -> int:\n return n\n", postponed)
checks.eq("future annotation remains string", inspect.get_annotations(postponed["build"]), {"n": "int", "return": "int"})
checks.eq("read trusted postponed hint", get_type_hints(postponed["build"])["return"] is int, True)
checks.finish("python-type-hints", runtime=sys.version, implementation=sys.implementation.name,
annotation_scope="actual CPython 3.12 interpreter observations; checker and editor states separate")
if __name__ == "__main__":
main()
所需环境:本地 Python 环境
当前源码 SHA256:2d775786ba225a59473859d0f34e605c37f29b2184ef28479f3cce630dce7ac4
当前源码有命名范围的实际运行记录;原文全部事实、其它平台和IDE界面仍待逐项验收。
常见错误与边界
- 命令、源码、当前解释器和具体平台分别核对,不能以单项运行推断整章验收。
练习与解答
使用本站实例修改一个条件,先写下预期,再实际运行。
展开参考解答
比较原始输出、修改后的输出及错误类型;未执行的平台和界面继续单列。