第 24 章 Type Hint
如果你有 TypeScript 基础,那么这一章应该会非常熟悉。
你已经写过:
typescript
function add(a: number, b: number): number {
return a + b;
}Python 可以写成:
python
def add(a: int, b: int) -> int:
return a + b看起来几乎是一回事。
但这里有一个非常重要的区别:
Python 的 Type Hint 默认不会在运行时阻止你传入错误类型。
这句话先记住。
24.1 Type Hint 到底是什么?
先看一个普通的 Python 函数:
python
def add(a, b):
return a + b我们看到:
text
a 是什么?
b 是什么?
返回什么?都不知道。
当然,我们可以靠函数名猜:
python
add(1, 2)可能是数字。
但也可以:
python
add("hello", "world")结果:
python
"helloworld"Python 并没有觉得有什么问题。
因为 Python 是动态类型语言。
现在增加类型提示:
python
def add(a: int, b: int) -> int:
return a + b这相当于告诉阅读代码的人和工具:
text
a → int
b → int
返回值 → int于是这个函数有了一份“类型契约”。
24.2 和 TypeScript 对比
TypeScript:
typescript
function add(a: number, b: number): number {
return a + b;
}Python:
python
def add(a: int, b: int) -> int:
return a + b对应关系:
text
TypeScript Python
number → int / float
string → str
boolean → bool
Array<T> → list[T]
Record<K, V> → dict[K, V]
tuple → tuple
T | None → T | None
A | B → A | B但是:
Python 类型提示主要服务于开发工具、静态检查器和阅读者,而不是 Python 解释器本身。
24.3 类型提示不会自动检查类型
看看:
python
def add(a: int, b: int) -> int:
return a + b你依然可以:
python
add("hello", "world")Python 不会因为:
text
str ≠ int就自动报类型错误。
它会返回:
python
"helloworld"所以:
python
def add(a: int, b: int) -> int:并不是:
“a 必须是 int。”
更准确地说:
“a 应该是 int。”
这就是 Type Hint 中非常重要的思想。
24.4 那 Type Hint 有什么用?
既然 Python 不强制,那为什么还要写?
因为工具可以理解它。
例如:
python
def add(a: int, b: int) -> int:
return a + b编辑器可以根据类型提示:
text
自动补全
类型检查
发现潜在错误
跳转定义
重构
代码提示例如你写:
python
result = add("hello", 10)Type checker 可以提醒:
text
Argument of type "str" cannot be assigned
to parameter "a" of type "int"这和 TypeScript 的体验就非常接近了。
24.5 Type Hint 的核心价值
可以把 Type Hint 理解成:
text
代码
↓
增加类型信息
↓
IDE / 静态检查器理解代码
↓
提前发现问题所以:
text
Type Hint最重要的作用不是:
让 Python 变成静态类型语言。
而是:
让 Python 代码变得更容易理解、更容易检查、更容易维护。
24.6 List
最简单的泛型容器:
python
numbers: list[int] = [1, 2, 3]表示:
text
numbers 是一个 list
list 里面的元素是 intTypeScript:
typescript
const numbers: number[] = [1, 2, 3];Python:
python
numbers: list[int] = [1, 2, 3]函数参数:
python
def total(numbers: list[int]) -> int:
return sum(numbers)意思:
text
numbers
↓
list
↓
每个元素
↓
int24.7 为什么不推荐写 List[int]?
以前 Python 常见:
python
from typing import List
numbers: List[int]现代 Python 推荐直接:
python
numbers: list[int]也就是:
text
旧写法:
List[int]
新写法:
list[int]同样:
python
dict[str, int]
tuple[int, str]
set[str]都可以直接使用。
如果项目需要兼容较老的 Python 版本,才可能看到旧式 typing.List 等写法。
24.8 Dict
例如:
python
scores: dict[str, int] = {
"Tom": 90,
"Alice": 95,
}意思:
text
key → str
value → intTypeScript:
typescript
const scores: Record<string, number> = {
Tom: 90,
Alice: 95,
};Python:
python
scores: dict[str, int] = {
"Tom": 90,
"Alice": 95,
}函数:
python
def get_score(scores: dict[str, int], name: str) -> int:
return scores[name]24.9 Tuple
tuple 和 list 最大的区别之一:
text
list
↓
通常表示一组相同类型的元素
tuple
↓
可以表示固定结构例如:
python
point: tuple[int, int] = (100, 200)表示:
text
第一个 → int
第二个 → intTypeScript 中类似:
typescript
const point: [number, number] = [100, 200];再看:
python
user: tuple[int, str] = (1001, "Tom")表示:
text
位置 1 → int
位置 2 → str这时候:
python
(1001, "Tom")和:
python
("Tom", 1001)类型不同。
24.10 tuple 的两种写法
注意:
python
tuple[int, str]表示:
text
固定两个元素:
int
str而:
python
tuple[int, ...]表示:
text
任意多个 int例如:
python
numbers: tuple[int, ...] = (1, 2, 3, 4, 5)这里:
text
元素数量:不限
元素类型:int这是一个很值得记住的小细节。
24.11 Optional
现在进入一个非常常见的类型:
python
Optional它表达的是:
这个值可能存在,也可能不存在。
例如:
python
from typing import Optional
def find_user(user_id: int) -> Optional[str]:
...表示:
text
返回值:
str
或者
None现代 Python 更推荐:
python
def find_user(user_id: int) -> str | None:
...这其实更直观。
text
str | None就是:
text
str
或者
NoneTypeScript 对应:
typescript
function findUser(id: number): string | null {
...
}Python:
python
def find_user(user_id: int) -> str | None:
...所以对于有 TS 基础的人:
text
T | null可以类比:
text
T | None24.12 Optional 这个名字有点容易误导
看到:
python
Optional[str]你可能以为:
“参数可以不传。”
不是。
例如:
python
def greet(name: Optional[str]):
...它表达的是:
text
name 可以是:
str
或者
None不代表:
text
name 可以省略如果想表达参数有默认值:
python
def greet(name: str | None = None):
...这里才同时表达:
text
类型:
str | None
默认值:
None24.13 Union
Union 表示:
一个值可以属于多个类型中的一个。
旧写法:
python
from typing import Union
def process(value: Union[int, str]):
...意思:
text
value 可以是:
int
或者
str现代 Python:
python
def process(value: int | str):
...更加简洁。
TypeScript:
typescript
function process(value: number | string) {
}几乎一模一样。
24.14 为什么推荐 |?
以前:
python
Union[int, str]现在:
python
int | str所以:
text
Union[int, str]可以理解成:
text
int | str而:
text
Optional[str]可以理解成:
text
str | None这让现代 Python 的类型表达越来越接近 TypeScript:
text
TS:
number | string
Python:
int | str24.15 类型缩小
TypeScript 很重要的一个概念:
typescript
function print(value: number | string) {
if (typeof value === "string") {
console.log(value.toUpperCase());
}
}Python 也可以做类似的事情:
python
def print_value(value: int | str) -> None:
if isinstance(value, str):
print(value.upper())这里:
python
isinstance(value, str)告诉人和类型检查器:
text
这里的 value 是 str所以:
python
value.upper()就合理了。
这是 Type Hint 和 Python 实际运行时结合得非常好的地方。
24.16 Literal
有时候:
text
str太宽了。
例如:
python
def set_mode(mode: str):
...理论上:
python
set_mode("hello")也可以。
但实际上我们只允许:
text
"light"
"dark"这时候可以:
python
from typing import Literal
def set_mode(mode: Literal["light", "dark"]) -> None:
...现在类型系统知道:
text
mode
↓
只能是
↓
"light"
或
"dark"TypeScript:
typescript
function setMode(mode: "light" | "dark") {
}Python:
python
def set_mode(mode: Literal["light", "dark"]) -> None:
...概念非常接近。
24.17 Literal 什么时候特别好用?
例如 API 参数:
python
def fetch_data(
format: Literal["json", "csv"]
):
...而不是:
python
def fetch_data(format: str):
...前者直接告诉 IDE:
text
format 有两个合法选择:
"json"
"csv"编辑器甚至可以给出自动补全。
24.18 TypeAlias
有时候一个类型太长。
例如:
python
UserId = int你可能希望表达:
text
UserId 是一种类型别名现代 Python 可以:
python
from typing import TypeAlias
UserId: TypeAlias = int之后:
python
def get_user(user_id: UserId):
...更复杂的情况:
python
UserData: TypeAlias = dict[str, str | int]然后:
python
def save_user(user: UserData) -> None:
...这样可以避免到处重复:
python
dict[str, str | int]24.19 类型别名不是新类型
这个区别非常重要。
python
UserId: TypeAlias = int并没有创造一个新的运行时类型。
所以:
text
UserId本质上还是:
text
int它只是:
给一个复杂类型起一个更有意义的名字。
可以把它理解成:
text
复杂类型
↓
起一个业务名称
↓
UserId这样代码的可读性会更好。
24.20 Generic
现在开始进入真正的类型系统。
假设我们有一个:
python
Box它可以装任何东西:
text
Box[int]
Box[str]
Box[User]我们希望:
python
Box[int]知道自己装的是:
text
int这就是泛型:
text
Generic例如:
python
from typing import Generic, TypeVar
T = TypeVar("T")
class Box(Generic[T]):
def __init__(self, value: T):
self.value = value现在:
python
box = Box(100)可以理解成:
text
Box[int]而:
python
box = Box("hello")可以理解成:
text
Box[str]24.21 为什么需要 Generic?
想象我们写一个容器。
没有泛型:
python
class Box:
def __init__(self, value):
self.value = value那么:
text
Box到底装什么?
text
int?
str?
User?
Order?不知道。
加入泛型:
python
class Box(Generic[T]):
def __init__(self, value: T):
self.value = valueT 就表示:
某一种还没有确定的类型。
使用的时候再确定。
text
Box[int]
↓
T = int
Box[str]
↓
T = str24.22 Generic 和 TypeScript 的对应
TypeScript:
typescript
class Box<T> {
constructor(public value: T) {}
}Python:
python
from typing import Generic, TypeVar
T = TypeVar("T")
class Box(Generic[T]):
def __init__(self, value: T):
self.value = value概念上非常接近。
所以如果你已经理解 TS 泛型:
typescript
Box<T>那么 Python:
python
Generic[T]就不难理解了。
24.23 Protocol
这是 Python 类型系统里非常值得掌握的一个概念。
而且:
它和传统的继承思维不一样。
假设我们有:
python
class Duck:
def quack(self):
print("quack")还有:
python
class Person:
def quack(self):
print("I'm pretending to be a duck")如果一个函数只关心:
text
有没有 quack()那么:
python
def make_it_quack(animal):
animal.quack()其实:
text
Duck可以。
text
Person也可以。
这就是:
鸭子类型。
24.24 Protocol 就是在类型系统里描述“鸭子类型”
例如:
python
from typing import Protocol
class Quacker(Protocol):
def quack(self) -> None:
...现在:
python
def make_it_quack(animal: Quacker) -> None:
animal.quack()任何拥有:
python
quack() -> None的对象,都可以符合这个 Protocol。
不需要:
python
class Duck(Quacker):这就是 Protocol 最有意思的地方。
24.25 Protocol 和继承有什么区别?
传统继承:
python
class Duck:
...
class Dog(Duck):
...这里关注的是:
text
Dog 是不是 Duck?而 Protocol 关注:
text
这个对象有没有我需要的行为?例如:
python
class Quacker(Protocol):
def quack(self) -> None:
...它关心:
text
有没有 quack()而不是:
text
是不是 Quacker 的子类所以:
text
继承
↓
is-a
Protocol
↓
behaves-like这和 Python 的鸭子类型思想非常契合。
24.26 Protocol 和 TypeScript interface 很像
如果你有 TypeScript 基础,这个类比非常有帮助。
TypeScript:
typescript
interface Quacker {
quack(): void;
}Python:
python
class Quacker(Protocol):
def quack(self) -> None:
...两者都在描述:
“我需要你具备什么能力。”
而不是:
“你必须继承我的类。”
24.27 一个真实一点的 Protocol
假设我们写一个函数:
python
def save(file):
file.write("hello")这个函数实际上不关心:
text
file 是什么具体类?它只关心:
text
有没有 write()于是:
python
from typing import Protocol
class Writable(Protocol):
def write(self, text: str) -> None:
...然后:
python
def save(file: Writable) -> None:
file.write("hello")任何满足这个结构的对象都可以。
这就是:
结构化类型(structural typing)
24.28 Python Type Hint 的核心思想
现在把前面的知识串起来:
text
基础类型
│
├── int
├── str
├── float
├── bool
│
容器
│
├── list[T]
├── dict[K, V]
├── tuple[T, ...]
│
组合类型
│
├── T | None
├── A | B
├── Literal[...]
│
类型抽象
│
├── TypeAlias
├── Generic
└── Protocol你会发现:
Type Hint 的目的,是越来越准确地描述“这个值应该长什么样”。
24.29 从 Any 开始,理解“类型信息”
有一个类型非常容易被滥用:
python
from typing import Any例如:
python
def process(value: Any):
...意思基本是:
这个值是什么类型都可以。
这当然很方便。
但也意味着:
text
类型检查器
↓
“好吧,我不管了。”所以:
python
Any并不是:
“高级类型。”
而更像:
“这里暂时不做类型约束。”
因此:
能写准确类型时,尽量不要到处写
Any。
24.30 一个典型的 Type Hint 演进过程
最开始:
python
def get_users():
return []完全不知道:
text
返回什么?加一点:
python
def get_users() -> list:
return []知道:
text
返回 list但不知道里面是什么。
继续:
python
def get_users() -> list[dict]:
return []知道:
text
list
↓
dict但 dict 的 key/value 仍然不明确。
继续:
python
def get_users() -> list[dict[str, int | str]]:
return []信息更多了。
但开始变得难读。
于是:
python
UserData: TypeAlias = dict[str, int | str]
def get_users() -> list[UserData]:
return []代码反而更清楚了。
这就是 Type Hint 很重要的一条原则:
类型应该帮助理解代码,而不是让代码变得更难读。
24.31 类型提示不是越多越好
例如:
python
x: int = 10如果上下文已经非常明显:
python
x = 10可能更好。
再比如:
python
name: str = "Tom"通常没必要。
因为 Python 和 IDE 都已经知道:
text
"Tom" → str所以 Type Hint 最有价值的地方往往是:
text
函数参数
函数返回值
复杂数据结构
公共 API
类
复杂业务类型而不是给每个变量都加类型。
24.32 函数参数是 Type Hint 最值得投入的地方
例如:
python
def calculate_price(
price: float,
quantity: int,
discount: float,
) -> float:
...读函数签名就能知道:
text
price
→ float
quantity
→ int
discount
→ float
返回
→ float你甚至不需要打开函数体。
这就是 Type Hint 非常大的价值:
函数签名本身就成为了一份 API 文档。
24.33 返回 None 要不要写?
如果函数没有返回值:
python
def log(message: str):
print(message)推荐:
python
def log(message: str) -> None:
print(message)这里:
text
None不是说:
函数什么都不返回。
而是说:
函数的返回值类型是
None。
24.34 None 和 Optional 的区别
看:
python
def log(message: str) -> None:
...表示:
text
返回值只能是 None而:
python
def find_user(user_id: int) -> User | None:
...表示:
text
返回 User
或者 None所以:
text
-> None和:
text
-> User | None完全不同。
24.35 Type Hint 最终会影响你的代码设计
假设:
python
def get_user(id: int) -> User | None:
...那么调用者自然会写:
python
user = get_user(100)
if user is None:
return
print(user.name)因为类型已经告诉我们:
text
user
↓
User | None必须处理:
text
None这就是类型系统非常有价值的地方:
类型信息会推动你写出更完整的代码。
24.36 Type Hint + IDE
真正使用 Type Hint 时,不应该只是:
text
写类型而应该:
text
Type Hint
↓
IDE
↓
自动补全
↓
静态检查
↓
重构
↓
发现问题常见的工具包括:
text
VS Code
Pyright
Pylance
mypy你不需要一开始全部学会。
但应该知道:
Python 的类型提示通常需要静态分析工具来发挥真正的价值。
24.37 Type Hint 和运行时检查是两回事
这是 Python 和 TypeScript 思维转换时最容易混淆的地方。
Type Hint:
python
def add(a: int, b: int) -> int:
...主要用于:
text
静态分析
IDE
代码阅读
文档而运行时:
python
add("hello", "world")Python 仍然可以执行。
如果你真的需要运行时验证,需要额外机制,例如:
text
dataclasses
pydantic等。
所以:
text
Type Hint不要理解成:
text
Runtime Type Check它们是两个不同的问题。
24.38 TypeScript 开发者最容易产生的误解
如果你来自 TypeScript,最容易产生这个想法:
“Python 写了
a: int,那 Python 就应该阻止传入字符串。”
不是。
Python:
python
def add(a: int, b: int) -> int:
...这里的:
text
: int主要是在说:
“请把它当作 int 来使用。”
而不是:
“运行时强制它必须是 int。”
这一区别一定要建立起来。
24.39 一个完整例子
现在综合一下:
python
from typing import Literal, Protocol, TypeAlias
UserId: TypeAlias = int
class UserRepository(Protocol):
def find_by_id(self, user_id: UserId) -> str | None:
...
def get_user(
repository: UserRepository,
user_id: UserId,
format: Literal["name", "id"],
) -> str | None:
user = repository.find_by_id(user_id)
if user is None:
return None
if format == "name":
return user
return str(user_id)这里已经同时使用:
text
TypeAlias
Protocol
Literal
Union / |
Optional / None
函数参数类型
返回值类型这就是现代 Python 类型系统开始发挥作用的地方。
24.40 学 Type Hint 不要死记 API
不要这样学习:
text
List
Dict
Tuple
Optional
Union
Literal
TypeAlias
Generic
Protocol然后背:
text
List 是什么
Dict 是什么
Tuple 是什么更好的学习方式是问:
我现在想描述什么?
例如:
“我需要一个整数列表。”
python
list[int]“我需要一个字符串到整数的映射。”
python
dict[str, int]“我需要一个固定的 (int, str) 结构。”
python
tuple[int, str]“可能没有值。”
python
str | None“可能是 int,也可能是 str。”
python
int | str“只能是这几个值。”
python
Literal["red", "green", "blue"]“这个复杂类型我想起个名字。”
python
TypeAlias“我需要一个可以装不同类型的通用容器。”
python
Generic“我只关心对象有没有某些方法。”
python
Protocol这才是 Type Hint 的正确学习方式。
24.41 一张 Type Hint 速查表
| 需求 | Python | TypeScript |
|---|---|---|
| 整数 | int | number |
| 字符串 | str | string |
| 布尔 | bool | boolean |
| 列表 | list[T] | T[] |
| 字典 | dict[K, V] | Record<K, V> |
| 固定 Tuple | tuple[int, str] | [number, string] |
| 可选值 | T | None | T | null |
| 联合类型 | A | B | A | B |
| 字面量 | Literal["a", "b"] | "a" | "b" |
| 类型别名 | TypeAlias | type |
| 泛型 | Generic[T] | Generic<T> |
| 结构类型 | Protocol | interface |
24.42 最重要的几个现代写法
如果你现在开始写现代 Python,优先掌握这些:
python
# list
numbers: list[int]
# dict
users: dict[int, str]
# tuple
point: tuple[int, int]
# optional
user: User | None
# union
value: int | str
# literal
mode: Literal["light", "dark"]
# type alias
UserId: TypeAlias = int
# generic
Box[T]
# protocol
class Repository(Protocol):
...其中:
text
list[T]
dict[K, V]
tuple[...]
T | None
A | B应该成为你的日常写法。
24.43 本章最重要的一个转变
没有 Type Hint 时,你看到:
python
def process(data):
...你的问题是:
text
data 是什么?加入类型:
python
def process(data: list[dict[str, int]]) -> bool:
...你马上知道:
text
data
↓
list
↓
dict
↓
key = str
value = int
返回
↓
bool所以 Type Hint 的核心价值可以浓缩成一句话:
让代码自己告诉你,它期待什么。
24.44 最后,用 TypeScript 的思维重新理解 Python
如果你已经会 TypeScript,那么可以建立下面这张映射:
text
TypeScript
│
├── number
│ ↓
│ Python int / float
│
├── string
│ ↓
│ Python str
│
├── T[]
│ ↓
│ list[T]
│
├── Record<K, V>
│ ↓
│ dict[K, V]
│
├── [A, B]
│ ↓
│ tuple[A, B]
│
├── A | B
│ ↓
│ A | B
│
├── T | null
│ ↓
│ T | None
│
├── "a" | "b"
│ ↓
│ Literal["a", "b"]
│
├── type
│ ↓
│ TypeAlias
│
├── Generic<T>
│ ↓
│ Generic[T]
│
└── interface
↓
Protocol但最后再强调一次:
text
TypeScript 类型
↓
编译阶段检查
↓
JavaScript 运行而 Python:
text
Python Type Hint
↓
静态分析工具
↓
Python 运行所以:
Python 的 Type Hint 是“可选的类型契约”,不是运行时类型系统。
掌握这个区别,你就真正开始从 TypeScript 的类型思维过渡到 Python 的类型思维了。
24.45 动手练习
不要只看语法。
自己写一个:
text
UserRepository要求:
1. UserId
使用:
python
TypeAlias定义:
text
UserId = int2. User
定义:
python
User至少包含:
text
id
name
email3. Repository
使用:
python
Protocol定义:
text
find_by_id()4. 查询函数
实现:
python
get_user(user_id)要求:
text
找到
↓
User
找不到
↓
None所以返回类型应该表达:
python
User | None5. 用户角色
假设角色只能是:
text
"admin"
"user"
"guest"使用:
python
Literal表达它。
6. 最后再做一个泛型
实现:
python
Repository[T]让它可以表示:
text
Repository[User]
Repository[Order]
Repository[Product]如果你能把这个练习写出来,那么:
text
list
dict
tuple
Optional
Union
Literal
TypeAlias
Generic
Protocol基本就不再是孤立的语法,而是一个完整的类型系统了。
本章心智模型
最后把整章压缩成一张图:
text
Type Hint
│
┌────────────┼────────────┐
│ │ │
基础类型 容器类型 组合类型
│ │ │
int / str list[T] A | B
float/bool dict[K,V] T | None
tuple[...] Literal
│
└────────────┬────────────┘
│
类型抽象与复用
│
┌────────┼────────┐
│ │ │
TypeAlias Generic Protocol
│ │ │
起名字 泛型 描述行为
│ │
└────┬───┘
│
静态分析
│
┌────────┴────────┐
│ │
IDE Type Checker
│ │
└────────┬────────┘
│
更可靠的代码记住:
Type Hint 的目标不是让 Python 看起来像 Java 或 TypeScript,而是用尽可能少的类型信息,让 Python 代码更容易被人和工具理解。