基础类型注解
from typing import List, Dict, Optional, Union
def greet(name: str) -> str:
return f"Hello, {name}"
def process_list(items: List[int]) -> Dict[str, int]:
return {"count": len(items)}
def find_user(id: int) -> Optional[Dict[str, str]]:
if id == 1:
return {"name": "zhangsan"}
return None联合类型与类型别名
# Python 3.10+
def handle(value: int | float | str) -> bool:
return bool(value)
# 类型别名
UserId = int
def get_user(uid: UserId) -> dict:
return {}自定义类型与 Protocol
from typing import Protocol
class Drawable(Protocol):
def draw(self) -> None: ...
def render(obj: Drawable) -> None:
obj.draw()使用 mypy 检查
pip install mypy
mypy my_script.py运行时忽略(TypeVar 与 cast)
from typing import cast
value: int = cast(int, some_func()) # 强制类型断言类型注解让代码更可读,结合 mypy 能提前发现类型错误,尤其适合大型项目。
