关于 python-typing-ops
面向 Python 开发者的类型提示参考技能,介绍现代化且便于维护的类型标注,并提供常见模式、检查命令及配置资源。
主要功能
- 01函数与集合的类型标注
- 02联合类型、TypedDict 与 Callable
- 03泛型、Protocol 与 TypeGuard
- 04mypy 和 pyright 使用说明
- 05配置资源与类型检查脚本
适用场景
- 01为函数和数据结构添加类型
- 02表示可选值与固定键字典
- 03定义泛型和结构化接口
- 04在项目环境中运行类型检查
安装
复制下面的命令,在终端中运行。
$
npx skills add https:/ / github.com/ 0xdarkmatter/ claude-mods --skill python-typing-ops安装后在 Claude Code 中输入/python-typing-ops确认已加载。
包含的文件
除 SKILL.md 外,安装时一起下载的参考资料和脚本。
assets/pyproject-typing.tomlreferences/generics-advanced.mdmypy-config.mdoverloads.mdprotocols-patterns.mdruntime-validation.mdtype-narrowing.mdscripts/check-types.sh详细介绍
Python 类型标注模式
为安全、文档完善的 Python 代码使用现代类型提示。
基本注解
# Variables
name: str = "Alice"
count: int = 42
items: list[str] = ["a", "b"]
mapping: dict[str, int] = {"key": 1}
# Function signatures
def greet(name: str, times: int = 1) -> str:
return f"Hello, {name}!" * times
# None handling
def find(id: int) -> str | None:
return db.get(id) # May return None
集合
from collections.abc import Sequence, Mapping, Iterable
# Use collection ABCs for flexibility
def process(items: Sequence[str]) -> list[str]:
"""Accepts list, tuple, or any sequence."""
return [item.upper() for item in items]
def lookup(data: Mapping[str, int], key: str) -> int:
"""Accepts dict or any mapping."""
return data.get(key, 0)
# Nested types
Matrix = list[list[float]]
Config = dict[str, str | int | bool]
可选类型与联合类型
# Modern syntax (3.10+)
def find(id: int) -> User | None:
pass
def parse(value: str | int | float) -> str:
pass
# With default 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): # All optional
debug: bool
log_level: str
class APIResponse(TypedDict):
data: Required[list[dict]]
error: NotRequired[str]
def process_user(user: UserDict) -> str:
return user["name"] # Type-safe key access
Callable
from collections.abc import Callable
# Function type
Handler = Callable[[str, int], bool]
def register(callback: Callable[[str], None]) -> None:
pass
# With keyword args (use Protocol instead)
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
# Bounded 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:
"""Accepts any object with read() method."""
data = source.read()
return json.loads(data)
# Works with file, BytesIO, custom classes
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 is now 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
# Constants
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 (run inside the project env)
uv run mypy src/ --strict
# pyright
uv run pyright src/
# In pyproject.toml
[tool.mypy]
strict = true
python_version = "3.11"
新兴工具:ty — Astral 基于 Rust 构建的类型检查器(与 uv +
ruff 使用相同的工具链),速度远快于 mypy。目前仍处于预览阶段(1.0 之前),因此 mypy 或
pyright 仍是生产环境的默认选择;但值得关注,也很容易试用:
uvx ty check。待其稳定后,可在新项目中采用。
其他资源
./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-ops- 类型安全的夹具和模拟
基于此技能继续学习:
python-async-ops- 异步类型注解python-fastapi-ops- Pydantic 模型和验证python-database-ops- SQLAlchemy 类型注解
评论
支持 Markdown