name: python-typing-patterns description: “Python类型提示与类型安全模式。触发词:类型提示、typing、TypeVar、Generic、Protocol、mypy、pyright、类型注解、overload、TypedDict。” compatibility: “Python 3.10+(使用联合语法 X | Y)。部分模式需要3.11+(Self、TypeVarTuple)。” allowed-tools: “读取 写入” depends-on: [] related-skills: [python-pytest-patterns]
Python 类型提示模式
用于编写安全、文档化的Python代码的现代类型提示。
基础注解
# 变量
name: str = "Alice"
count: int = 42
items: list[str] = ["a", "b"]
mapping: dict[str, int] = {"key": 1}
# 函数签名
def greet(name: str, times: int = 1) -> str:
return f"Hello, {name}!" * times
# None处理
def find(id: int) -> str | None:
return db.get(id) # 可能返回None
集合类型
from collections.abc import Sequence, Mapping, Iterable
# 使用集合抽象基类以获得灵活性
def process(items: Sequence[str]) -> list[str]:
"""接受列表、元组或任何序列。"""
return [item.upper() for item in items]
def lookup(data: Mapping[str, int], key: str) -> int:
"""接受字典或任何映射。"""
return data.get(key, 0)
# 嵌套类型
Matrix = list[list[float]]
Config = dict[str, str | int | bool]
Optional 与 Union
# 现代语法(3.10+)
def find(id: int) -> User | None:
pass
def parse(value: str | int | float) -> str:
pass
# 默认值为None
def fetch(url: str, timeout: float | None = None) -> bytes:
pass
TypedDict
from typing import TypedDict, Required, NotRequired
class UserDict(TypedDict):
id: int
name: str
email: str | None
class ConfigDict(TypedDict, total=False): # 所有字段可选
debug: bool
log_level: str
class APIResponse(TypedDict):
data: Required[list[dict]]
error: NotRequired[str]
def process_user(user: UserDict) -> str:
return user["name"] # 类型安全的键访问
Callable
from collections.abc import Callable
# 函数类型
Handler = Callable[[str, int], bool]
def register(callback: Callable[[str], None]) -> None:
pass
# 带关键字参数(建议使用Protocol替代)
from typing import Protocol
class Processor(Protocol):
def __call__(self, data: str, *, verbose: bool = False) -> int:
...
泛型
from typing import TypeVar
T = TypeVar("T")
def first(items: list[T]) -> T | None:
return items[0] if items else None
# 有界TypeVar
from typing import SupportsFloat
N = TypeVar("N", bound=SupportsFloat)
def average(values: list[N]) -> float:
return sum(float(v) for v in values) / len(values)
Protocol(结构类型)
from typing import Protocol
class Readable(Protocol):
def read(self, n: int = -1) -> bytes:
...
def load(source: Readable) -> dict:
"""接受任何具有read()方法的对象。"""
data = source.read()
return json.loads(data)
# 适用于文件、BytesIO、自定义类
load(open("data.json", "rb"))
load(io.BytesIO(b"{}"))
类型守卫
from typing import TypeGuard
def is_string_list(val: list[object]) -> TypeGuard[list[str]]:
return all(isinstance(x, str) for x in val)
def process(items: list[object]) -> None:
if is_string_list(items):
# items 现在被识别为 list[str]
print(", ".join(items))
Literal 与 Final
from typing import Literal, Final
Mode = Literal["read", "write", "append"]
def open_file(path: str, mode: Mode) -> None:
pass
# 常量
MAX_SIZE: Final = 1024
API_VERSION: Final[str] = "v2"
快速参考
| 类型 | 使用场景 |
|---|---|
X | None |
可选值 |
list[T] |
同质列表 |
dict[K, V] |
字典 |
Callable[[Args], Ret] |
函数类型 |
TypeVar("T") |
泛型参数 |
Protocol |
结构类型 |
TypedDict |
具有固定键的字典 |
Literal["a", "b"] |
仅允许特定值 |
Final |
不可重新赋值 |
类型检查器命令
# mypy
mypy src/ --strict
# pyright
pyright src/
# 在 pyproject.toml 中配置
[tool.mypy]
strict = true
python_version = "3.11"
附加资源
./references/generics-advanced.md- TypeVar、ParamSpec、TypeVarTuple./references/protocols-patterns.md- 结构类型、运行时协议./references/type-narrowing.md- 守卫、isinstance、assert./references/mypy-config.md- mypy/pyright 配置./references/runtime-validation.md- Pydantic v2、typeguard、beartype./references/overloads.md- @overload 装饰器模式
脚本
./scripts/check-types.sh- 使用常用选项运行类型检查器
资源文件
./assets/pyproject-typing.toml- 推荐的 mypy/pyright 配置
另请参阅
这是一个基础技能,没有先决条件。
相关技能:
python-pytest-patterns- 类型安全的夹具和模拟
基于此技能构建:
python-async-patterns- 异步类型注解python-fastapi-patterns- Pydantic 模型和验证python-database-patterns- SQLAlchemy 类型注解