8.1 渐进式静态类型:基础类型标注、typing 模块(Union、Optional、Generic)详解
本节目录
欢迎回到 HelloWorld 技术社区(www.helloworld.net) 《Python 现代开发实战》专栏。
Python 依然是动态语言,但自 Python 3.5 引入类型注解并在 3.10–3.13 不断进化后,“现代 Python = 动态语言的灵活 + 静态类型提示的严谨” 已成行业共识。
现代 Python 3.12+ 极简类型标注写法
现在已经不需要从 typing 导入大写的 List、Dict、Optional 或 Union 了,直接用内置容器与 | 联合符号即可:
from collections.abc import Callable, Sequence
from typing import Generic, TypeVar
T = TypeVar("T")
# 1. 使用内置 list / dict 和 | None 联合类型
def find_user_by_id(user_id: int, cache: dict[int, str]) -> str | None:
return cache.get(user_id)
# 2. 遵循“参数宽容(接收 Sequence),返回精确(返回 list)”原则
def filter_valid_items(items: Sequence[str], predicate: Callable[[str], bool]) -> list[str]:
return [item for item in items if predicate(item)]
# 3. 泛型分页响应模型(Python 3.12+ 支持全新的 class Page[T]: 极简泛型语法!)
class PageResult[T]:
def __init__(self, items: list[T], total: int) -> None:
self.items = items
self.total = total
💬 HelloWorld 社区实战打卡
写出一个接收任意映射类型(Mapping[str, int])并返回最大值的键名的函数签名(含完整类型注解,当字典为空时返回 None)。带 #Python专栏打卡 留言!