一、类型注解的核心价值
-
代码可读性:明确函数输入输出类型
-
静态检查:配合mypy提前发现类型错误
-
IDE支持:提升代码补全和重构能力
-
文档替代:类型即文档的现代编程理念
二、基础语法规范
def greet(name: str, times: int = 1) -> str:return "\n".join([f"Hello {name}"] * times)class User:def __init__(self, uid: int, name: str) -> None:self.uid = uidself.name = name
三、高级类型应用
-
复合类型:使用typing模块
-
List[str], Dict[str, int]
-
Optional[str] = Union[str, None]
-
Callable[[int, str], bool]
-
-
类型别名:
UserID = NewType('UserID', int) Coordinates = Tuple[float, float]
-
泛型支持:
T = TypeVar('T') class Stack(Generic[T]):def push(self, item: T) -> None: ...def pop(self) -> T: ...
四、工程最佳实践
-
渐进式注解:从核心模块开始
-
严格模式配置:
[mypy] disallow_untyped_defs = True warn_return_any = True
-
类型存根文件(.pyi)的使用
-
与Pydantic的结合:数据验证场景
五、常见问题解决方案
-
循环引用问题:使用字符串字面量
def process_user(user: 'User') -> None: ...
-
动态类型处理:TypeDict和Protocol