欢迎来到程序员中文网!

首页 Linux Mysql C++ Python PHP JavaScript 资源下载 动态 开源推荐
我要投稿 投诉建议

Python 类型注解与 mypy 静态检查

时间:2026年08月12日 04:46:50 浏览:0

基础类型注解


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 能提前发现类型错误,尤其适合大型项目。