类型注解深入
TypeAlias/NewType、TypedDict、泛型 TypeVar、mypy 检查
类型提示 (Type Hints)
类型提示让代码意图更明确,IDE 自动补全更智能,是现代 Python 的标配。
学完本章你将掌握: 基本类型注解、Optional/Union、泛型容器、Protocol。
一、基本类型注解
python
def greet(name: str, age: int) -> str:
return f"{name},{age}岁"
# 类型提示不影响运行,只是给开发者和工具看的
print(greet("小明", 20))
# 变量也可以注解
scores: list[int] = [90, 85, 92]
user: dict[str, str] = {"name": "小明"}
nothing: None = None
二、Optional 与 Union
python
from typing import Optional, Union
# Optional[X] = X | None
def find_user(id: int) -> Optional[str]:
users = {1: "小明", 2: "小红"}
return users.get(id) # 可能返回 None
# Union 表示"多个类型之一"
def format_value(val: Union[int, float, str]) -> str:
return str(val)
💡 Python 3.10+ 可以直接写
str | None代替Optional[str]。
三、容器类型
python
names: list[str] = ["a", "b"]
scores: dict[str, int] = {"小明": 90}
points: tuple[int, int] = (10, 20)
items: set[int] = {1, 2, 3}
matrix: list[list[int]] = [[1,2],[3,4]]
四、函数类型
python
from typing import Callable
# 第二个参数是一个函数:接受 int 返回 int
def apply(func: Callable[[int], int], val: int) -> int:
return func(val)
def double(x: int) -> int:
return x * 2
print(apply(double, 5)) # 10
五、TypedDict——类型化字典
python
from typing import TypedDict
class User(TypedDict):
name: str
age: int
email: str
def process(user: User) -> str:
return f"{user['name']}, {user['age']}岁" # IDE 有提示!
六、类型别名
python
type UserId = int
type JsonDict = dict[str, object]
def get_user(id: UserId) -> JsonDict:
return {"id": id, "name": "小明"}
小结
- 类型提示不强制检查,但极大提升可读性
Optional[X]/X | None表示可为空list[X]dict[K,V]表示容器元素类型- 搭配 mypy 做静态类型检查效果更佳