Python 的 `typing` 库
Python 的 typing
库是用于支持类型提示(Type Hints)的核心模块,自 Python 3.5 引入。它的主要目的是让开发者能够为变量、函数参数、返回值等标注类型信息,从而提高代码的可读性、可维护性,并借助静态类型检查工具(如 mypy
)发现潜在的类型错误。
核心功能
-
类型注解(Type Annotations)
允许为变量、函数参数和返回值添加类型信息:def greet(name: str) -> str: return f"Hello, {name}"
-
复合类型支持
使用泛型(Generics)和容器类型定义复杂结构:from typing import List, Dict def process_data(data: List[Dict[str, int]]) -> None: for item in data: print(item)
-
联合类型(Union Types)
表示一个值可以是多种类型之一:from typing import Union def parse_number(value: Union[int, str]) -> float: return float(value)
-
可选类型(Optional)
表示值可以是某种类型或None
:from typing import Optional def find_user(user_id: int) -> Optional[str]: # 可能返回用户名或 None return users.get(user_id)
-
类型别名(Type Aliases)
为复杂类型定义简短的别名:UserProfile = Dict[str, Union[str, int, List[str]]]
-
泛型(Generics)
创建可重用的泛型类或函数:from typing import TypeVar, Generic T = TypeVar('T') class Box(Generic[T]): def __init__(self, content: T): self.content = content
-
回调函数类型(Callable)
标注函数作为参数的类型:from typing import Callable def on_event(callback: Callable[[int, str], data: int) -> None: callback(data, "event")
常用工具
Any
: 表示任意类型(禁用类型检查)。NewType
: 创建自定义类型(如UserId = NewType('UserId', int)
)。Literal
: 指定具体的字面值(如Literal["success", "error"]
)。TypedDict
: 定义字典的键和值类型(Python 3.8+)。Protocol
: 定义接口协议(类似抽象类,PEP 544)。
Python 3.10+ 的新语法
Python 3.10 简化了部分类型语法,减少对 typing
的依赖:
|
替代Union
:def square(num: int | float) -> int | float: return num ** 2
list
替代List
:def sum_numbers(nums: list[int]) -> int: return sum(nums)
静态类型检查工具
类型提示本身不影响运行时行为,但可通过工具(如 mypy
、pyright
)进行静态检查:
pip install mypy
mypy your_script.py
示例代码
from typing import Optional, Union, List
def calculate_average(numbers: List[Union[int, float]]) -> Optional[float]:
if not numbers:
return None
return sum(numbers) / len(numbers)
# 使用类型别名
Vector = List[float]
def scale_vector(v: Vector, scalar: float) -> Vector:
return [x * scalar for x in v]
注意事项
- 类型提示是可选功能,Python 仍是动态类型语言。
- 运行时不会强制检查类型(除非手动验证)。
- 类型提示对性能无影响。
通过 typing
库,Python 在保留灵活性的同时,显著提升了大型项目的可维护性。建议结合 IDE(如 PyCharm 或 VS Code)的自动补全和类型检查功能使用。