【Python】typing 模块:类型注解支持库,用于提供静态类型提示(type hinting)

Python 中的 typing 模块

typing 模块是 Python 的类型注解支持库,用于提供静态类型提示(type hinting),增强代码的可读性、可维护性和开发工具的静态检查能力。从 Python 3.5 开始引入,后续版本不断扩展,Python 3.9+ 支持更多简化语法。


1. 基本语法:函数注解

def add(x: int, y: int) -> int:
    return x + y
  • x: int 表示 x 应该是整数
  • -> int 表示函数返回一个整数

这不会限制运行时类型,但工具(如 mypy, pyright, IDE)可以进行静态检查。


2. 常用类型注解

类型 说明
int, float, str, bool 基础类型
List[T] 列表,如 List[int] 表示整数列表
Dict[K, V] 字典,如 Dict[str, int]
Tuple[T1, T2] 元组,如 Tuple[int, str]
Set[T] 集合,如 Set[str]
Optional[T] 可为 T 或 None,如 Optional[int]
Union[T1, T2] 可为多个类型之一,如 Union[int, str]
Any 任意类型
Callable 可调用对象(如函数)
Literal 精确指定某些值(3.8+)
TypeVar 泛型类型变量
Annotated 注解扩展(3.9+)

从 Python 3.9 起,内置容器类型支持原生注解:list[int] 替代 List[int],无需引入 typing.List


3. 示例:常见类型注解

3.1 列表和字典

from typing import List, Dict

def process(nums: List[int]) -> Dict[str, int]:
    return {
    
    "sum": sum(nums)}

3.2 可选值和联合类型

from typing import Optional, Union

def greet(name: Optional[str]) -> str:
    if name:
        return f"Hello, {
      
      name}"
    return "Hello, stranger"

def parse(value: Union[int, str]) -> str:
    return str(value)

3.3 元组和集合

from typing import Tuple, Set

def get_info() -> Tuple[str, int]:
    return ("Tom", 25)

def unique_names(names: Set[str]) -> int:
    return len(names)

3.4 函数类型:Callable

from typing import Callable

def apply(func: Callable[[int, int], int], x: int, y: int) -> int:
    return func(x, y)

# 使用
print(apply(lambda a, b: a + b, 3, 5))  # 8

3.5 Any 类型

from typing import Any

def to_str(data: Any) -> str:
    return str(data)

3.6 使用 Literal(Python 3.8+)

from typing import Literal

def draw_shape(shape: Literal["circle", "square"]) -> None:
    print(f"Drawing {
      
      shape}")

4. 泛型编程:TypeVar

from typing import TypeVar, List

T = TypeVar("T")

def get_first(items: List[T]) -> T:
    return items[0]
  • 泛型 T 可以是任意类型,调用时会自动推断类型。

5. 注解类属性

from typing import List
from dataclasses import dataclass

@dataclass
class Student:
    name: str
    scores: List[int]

6. 注解变量(Python 3.6+)

age: int = 25
names: list[str] = ["Alice", "Bob"]

7. NewType:定义逻辑上的新类型

from typing import NewType

UserId = NewType("UserId", int)

def get_user(user_id: UserId) -> str:
    return f"User {
      
      user_id}"

8. Annotated(Python 3.9+)

from typing import Annotated

def process(name: Annotated[str, "username"]) -> None:
    ...

9. 静态类型检查工具

要让类型注解真正发挥作用,推荐使用类型检查工具:

  • mypypip install mypy
  • pyright / pylance:VS Code 插件
  • pyrepytype
mypy your_script.py

10. 总结:常用类型注解速查表

类型 示例
基本类型 int, str, bool
列表 List[int] / list[str]
字典 Dict[str, int]
元组 Tuple[str, int]
可选值(含 None) Optional[str]
联合类型 Union[int, float]
函数类型 Callable[[int], bool]
泛型 TypeVar, Generic
任意类型 Any
精确定义的值 Literal["yes", "no"]
类型注释变量 x: int = 10

typing 模块是 Python 静态类型系统的核心,让代码更清晰、更易维护,尤其适合中大型项目、团队协作或在使用编辑器/IDE 提供的类型检查、自动补全时提升开发体验。