Python typing模块
typing模块提供类型注解的高级工具,增强代码可读性和类型安全。
基本泛型类型
Python
from typing import List, Dict, Tuple, Set
# 列表类型
names: List[str] = ['Alice', 'Bob']
numbers: List[int] = [1, 2, 3]
# 字典类型
scores: Dict[str, int] = {'Alice': 90, 'Bob': 85}
# 元组类型
point: Tuple[int, int] = (10, 20)
record: Tuple[str, int, float] = ('Alice', 25, 90.5)
# 集合类型
unique_nums: Set[int] = {1, 2, 3}
Optional 可选类型
Python
from typing import Optional
# Optional[T] 表示 T 或 None
def find_user(id: int) -> Optional[str]:
if id > 0:
return 'Alice'
return None
result: Optional[str] = find_user(1)
Union 联合类型
Python
from typing import Union
# Union[T1, T2] 表示多种类型之一
def process(value: Union[int, str]) -> str:
return str(value)
# Python 3.10+ 可用 | 语法
def process_new(value: int | str) -> str:
return str(value)
Callable 函数类型
Python
from typing import Callable
# Callable[[参数类型], 返回类型]
def apply(func: Callable[[int], int], value: int) -> int:
return func(value)
def square(x: int) -> int:
return x ** 2
result = apply(square, 5)
Any 任意类型
Python
from typing import Any
# Any 表示任意类型
def process(value: Any) -> Any:
return value
# 使用时建议限制范围
def process_any(value: Any) -> str:
return str(value)
TypeVar 类型变量
Python
from typing import TypeVar, Generic
T = TypeVar('T')
# 泛型函数
def first(items: List[T]) -> T:
return items[0]
# 泛型类
class Container(Generic[T]):
def __init__(self, value: T):
self.value = value
def get(self) -> T:
return self.value
c: Container[int] = Container(10)
Protocol 协议
Python
from typing import Protocol
class SupportsRead(Protocol):
def read(self) -> str:
...
def process(reader: SupportsRead) -> str:
return reader.read()
class FileReader:
def read(self) -> str:
return "file content"
# FileReader 实现了 SupportsRead 协议
process(FileReader())
Literal 字面量类型
Python
from typing import Literal
# Literal 表示具体的值
def set_mode(mode: Literal['read', 'write', 'append']) -> None:
print(f"Mode: {mode}")
set_mode('read') # OK
set_mode('delete') # 类型检查报错
Final 常量标注
Python
from typing import Final
# Final 表示不应修改的值
MAX_SIZE: Final[int] = 100
class Config:
VERSION: Final[str] = '1.0'
TypedDict 字典类型
Python
from typing import TypedDict
class Person(TypedDict):
name: str
age: int
active: bool
# 字典必须包含指定键
person: Person = {'name': 'Alice', 'age': 25, 'active': True}
类型别名
Python
from typing import TypeAlias
# 创建类型别名
Vector: TypeAlias = List[float]
Matrix: TypeAlias = List[Vector]
def normalize(v: Vector) -> Vector:
return v
v: Vector = [1.0, 2.0, 3.0]
常用类型汇总
| 类型 | 说明 |
|---|---|
| List[T] | 列表 |
| Dict[K, V] | 字典 |
| Tuple[T, ...] | 元组 |
| Set[T] | 集合 |
| Optional[T] | T 或 None |
| Union[T1, T2] | 多种类型之一 |
| Callable[[Args], Ret] | 函数类型 |
| Any | 任意类型 |
| TypeVar | 类型变量 |
| Protocol | 协议类型 |
| Literal | 字面量类型 |
| Final | 常量标注 |
| TypedDict | 字典类型 |
要点总结
- typing模块提供泛型类型用于复杂类型注解
List[T]、Dict[K, V]、Tuple[T, ...]常用泛型Optional[T]表示值可能为 NoneUnion[T1, T2]表示多种类型之一Callable[[Args], Ret]注解函数类型TypeVar创建类型变量支持泛型Protocol定义结构化类型TypedDict精确注解字典键值类型- Python 3.10+ 可用
|语法替代 Union
📝 发现内容有误?点击此处直接编辑