什么是 Python Type Hints(类型注解)
Type Hints(类型注解)是 Python 中用于指定变量、函数参数和返回值预期类型的一种机制。它能够显著提升代码的可读性、可靠性和软件质量。尽管 Python 仍然是动态类型语言,但显式标注类型有助于在开发阶段避免许多潜在错误。
为什么需要类型注解
Python 以其灵活性著称,但这也常常因数据类型不匹配而导致隐藏的 bug。来看一个没有类型注解的例子:
def add(a, b):
return a + b
print(add(5, 10)) # 15
print(add("5", "10")) # '510' — 出乎意料的结果
表达式 add("5", "10") 不会报错,但结果可能让开发者感到意外。
Type Hints 主要解决以下问题:
- 显式指定类型:明确函数参数和返回值的类型
- 提升代码可读性:方便团队协作理解代码
- 静态分析:在程序运行前发现类型错误
- IDE 自动补全:获得更精准的代码提示
- API 文档化:无需额外注释即可说明接口
Type Hints 基础用法示例
函数注解
def add(a: int, b: int) -> int:
return a + b
def calculate_area(radius: float) -> float:
return 3.14159 * radius ** 2
def format_greeting(name: str) -> str:
return f"你好, {name}!"
变量注解
name: str = "Alice"
age: int = 30
pi: float = 3.14159
is_active: bool = True
集合类型操作
from typing import List, Dict, Tuple, Set
def process_scores(scores: List[int]) -> float:
return sum(scores) / len(scores)
def get_user_data() -> Dict[str, str]:
return {"name": "John", "email": "john@example.com"}
def get_coordinates() -> Tuple[float, float]:
return (10.5, 20.3)
def unique_values(items: List[str]) -> Set[str]:
return set(items)
Type Hints 进阶用法
Optional 和 Union
from typing import Optional, Union
def greet(name: Optional[str] = None) -> str:
if name:
return f"你好, {name}!"
return "你好, 游客!"
def process_value(value: Union[int, float, str]) -> str:
return str(value)
# Python 3.10+ 中可以使用 | 运算符
def process_new_syntax(value: int | float | str) -> str:
return str(value)
Callable 类型
from typing import Callable
def apply_function(func: Callable[[int, int], int], a: int, b: int) -> int:
return func(a, b)
def multiply(x: int, y: int) -> int:
return x * y
result = apply_function(multiply, 5, 3) # 15
Generic 泛型
from typing import TypeVar, Generic, List
T = TypeVar('T')
class Stack(Generic[T]):
def __init__(self) -> None:
self.items: List[T] = []
def push(self, item: T) -> None:
self.items.append(item)
def pop(self) -> T:
if not self.items:
raise IndexError("栈为空")
return self.items.pop()
def is_empty(self) -> bool:
return len(self.items) == 0
# 使用示例
int_stack = Stack[int]()
int_stack.push(42)
类中的类型注解
from typing import List, Optional
from dataclasses import dataclass
class Person:
def __init__(self, name: str, age: int, email: Optional[str] = None) -> None:
self.name = name
self.age = age
self.email = email
def get_info(self) -> str:
return f"姓名: {self.name}, 年龄: {self.age}"