Python 类型注解与 mypy 静态类型检查
类型注解提高代码可读性,结合 mypy 可实现静态类型检查。
1. 基本注解
from typing import List, Dict, Optional, Union
def greet(name: str) -> str:
return f'Hello, {name}'
def process(items: List[int]) -> Dict[str, int]:
return {'count': len(items)}
def find_user(id: int) -> Optional[Dict[str, str]]:
if id == 1:
return {'name': '张三'}
return None2. 联合类型与别名
# Python 3.10+
def handle(value: int | float | str) -> bool:
return bool(value)
# 类型别名
UserId = int
def get_user(uid: UserId) -> dict:
return {}3. 自定义类型(Protocol)
from typing import Protocol
class Drawable(Protocol):
def draw(self) -> None: ...
def render(obj: Drawable) -> None:
obj.draw()4. 使用 mypy
pip install mypy
mypy script.py5. 运行时忽略(cast)
from typing import cast
value: int = cast(int, some_func())类型注解有助于大型项目的维护和协作。
