Python 类型提示实践指南¶
类型提示(Type Hints)让 Python 代码更易读、更易维护,还能借助工具在运行前发现 bug。
基础类型¶
def greet(name: str, times: int = 1) -> str:
return (f"Hello, {name}! " * times).strip()
age: int = 25
scores: list[float] = [98.5, 87.0, 92.3]
config: dict[str, str] = {"theme": "dark"}
进阶用法¶
Optional 和 Union¶
from typing import Optional
def find_user(user_id: int) -> Optional[dict]:
"""找不到用户时返回 None"""
users = {1: {"name": "Alice"}, 2: {"name": "Bob"}}
return users.get(user_id)
TypeVar 与泛型¶
from typing import TypeVar, Sequence
T = TypeVar("T")
def first(items: Sequence[T]) -> T:
return items[0]
dataclass + 类型提示¶
from dataclasses import dataclass
@dataclass
class Article:
title: str
author: str
views: int = 0
tags: list[str] | None = None
工具链¶
| 工具 | 用途 |
|---|---|
| mypy | 静态类型检查 |
| pyright | VS Code 集成检查 |
| beartype | 运行时类型校验 |
建议¶
- 新项目从一开始就加类型提示
- 老项目优先给公共 API 和复杂函数加
- 配合
mypy --strict逐步提高覆盖率