Python 的 typing
模块提供了类型提示(Type Hints)支持,它可以帮助开发者编写更清晰、更易维护的代码,并允许静态类型检查器在代码运行前发现潜在的错误。
基本类型注解 #
# 变量类型注解
name: str = "Alice"
age: int = 30
height: float = 1.75
is_student: bool = True
# 函数参数和返回值的类型注解
def greet(name: str) -> str:
return f"Hello, {name}"
def calculate_area(length: float, width: float) -> float:
return length * width
复合类型 #
from typing import List, Dict, Tuple, Set
# 列表
numbers: List[int] = [1, 2, 3, 4, 5]
# 字典
person: Dict[str, str] = {"name": "Alice", "city": "New York"}
# 元组
coordinates: Tuple[float, float] = (40.7128, -74.0060)
# 集合
unique_numbers: Set[int] = {1, 2, 3, 4, 5}
更复杂的类型 #
from typing import Union, Optional, Any, Callable
# Union: 多个可能类型
def process_input(value: Union[str, int]) -> None:
pass
# Optional: 可能是None
def find_user(user_id: int) -> Optional[str]:
# 返回用户名或None
pass
# Any: 任意类型
def process_data(data: Any) -> Any:
pass
# Callable: 函数类型
def apply_function(func: Callable[[int, int], int], x: int, y: int) -> int:
return func(x, y)
自定义类型和类型别名 #
from typing import TypeVar, NewType
# 类型别名
UserId = int
users: Dict[UserId, str] = {1: "Alice", 2: "Bob"}
# 新类型
UserId = NewType('UserId', int)
user_id = UserId(12345)
# 泛型类型变量
T = TypeVar('T')
def first_item(items: List[T]) -> T:
return items[0]
高级类型特性 #
from typing import Literal, Final
# Literal: 特定值
def set_direction(direction: Literal["north", "south", "east", "west"]) -> None:
pass
# Final: 不可重新赋值
MAX_SIZE: Final[int] = 100
类与类型提示 #
from typing import ClassVar
class Person:
# 类变量类型注解
species: ClassVar[str] = "Homo sapiens"
def __init__(self, name: str, age: int) -> None:
self.name = name
self.age = age
def get_birth_year(self) -> int:
return 2023 - self.age
实际应用示例 #
from typing import List, Dict, Optional
def process_users(users: List[Dict[str, str]]) -> List[str]:
"""处理用户列表,返回用户名列表"""
return [user["name"] for user in users if "name" in user]
def calculate_stats(data: List[float]) -> Dict[str, float]:
"""计算数据的统计信息"""
return {
"mean": sum(data) / len(data),
"max": max(data),
"min": min(data)
}
# 使用类型提示的完整示例
class Database:
def __init__(self, connection_string: str) -> None:
self.connection_string = connection_string
def query(self, query: str) -> Optional[List[Dict]]:
# 模拟数据库查询
return [{"id": 1, "name": "Alice"}, {"id": 2, "name": "Bob"}]
def get_user_names(db: Database) -> List[str]:
results = db.query("SELECT name FROM users")
if results is None:
return []
return [user["name"] for user in results]
使用建议 #
- 逐步采用:可以在现有项目中逐步添加类型提示
- 使用静态类型检查器:如
mypy
来检查类型错误 - 保持一致性:在团队中约定类型提示的使用规范
- 避免过度使用:对于简单明显的代码,可以省略类型提示
类型提示不会影响Python代码的运行性能,但它们可以大大提高代码的可读性和可维护性,特别是在大型项目中。