SKILL.md
readonly只读
name
python-pro
description
在构建需要类型安全、异步编程或健壮错误处理的 Python 3.11+ 应用程序时使用。生成带有类型注解的 Python 代码,在严格模式下配置 mypy,使用 pytest 编写包含 fixture 和 mock 的测试套件,并通过 black 和 ruff 验证代码。适用于类型提示、async/await 模式、数据类、依赖注入、日志配置和结构化错误处理。
Python Pro
专注于类型安全、异步优先、生产就绪代码的现代 Python 3.11+ 专家。
何时使用此技能
- 编写具有完整类型覆盖的类型安全 Python 代码
- 为 I/O 操作实现 async/await 模式
- 使用 fixture 和 mock 设置 pytest 测试套件
- 创建包含推导式、生成器、上下文管理器的 Pythonic 代码
- 使用 Poetry 和正确的项目结构构建包
- 性能优化和分析
核心工作流
- 分析代码库 — 检查结构、依赖、类型覆盖、测试套件
- 设计接口 — 定义协议、数据类、类型别名
- 实现 — 编写带有完整类型提示和错误处理的 Pythonic 代码
- 测试 — 创建覆盖超过 90% 的全面 pytest 套件
- 验证 — 运行
mypy --strict、black、ruff- 如果 mypy 失败:修复报告的类型错误并重新运行,然后再继续
- 如果测试失败:调试断言,更新 fixture,并迭代直到通过
- 如果 ruff/black 报告问题:应用自动修复,然后重新验证
参考指南
根据上下文加载详细指导:
| 主题 | 参考 | 加载时机 |
|---|---|---|
| 类型系统 | references/type-system.md |
类型提示、mypy、泛型、Protocol |
| 异步模式 | references/async-patterns.md |
async/await、asyncio、任务组 |
| 标准库 | references/standard-library.md |
pathlib、dataclasses、functools、itertools |
| 测试 | references/testing.md |
pytest、fixture、mock、parametrize |
| 打包 | references/packaging.md |
poetry、pip、pyproject.toml、分发 |
约束
必须做
- 所有函数签名和类属性都要有类型提示
- 符合 PEP 8 规范,使用 black 格式化
- 完整的文档字符串(Google 风格)
- 使用 pytest 实现超过 90% 的测试覆盖率
- 使用
X | None代替Optional[X](Python 3.10+) - 对 I/O 密集型操作使用 async/await
- 使用数据类代替手动 init 方法
- 使用上下文管理器处理资源
禁止做
- 在公共 API 上跳过类型注解
- 使用可变的默认参数
- 不正确地混合同步和异步代码
- 忽略严格模式下的 mypy 错误
- 使用裸的 except 子句
- 硬编码密钥或配置
- 使用已弃用的标准库模块(使用 pathlib 而非 os.path)
代码示例
带错误处理的类型注解函数
from pathlib import Path
def read_config(path: Path) -> dict[str, str]:
"""从文件读取配置。
Args:
path: 配置文件路径。
Returns:
解析后的键值配置项。
Raises:
FileNotFoundError: 如果配置文件不存在。
ValueError: 如果某行无法解析。
"""
config: dict[str, str] = {}
with path.open() as f:
for line in f:
key, _, value = line.partition("=")
if not key.strip():
raise ValueError(f"无效的配置行: {line!r}")
config[key.strip()] = value.strip()
return config
带验证的数据类
from dataclasses import dataclass, field
@dataclass
class AppConfig:
host: str
port: int
debug: bool = False
allowed_origins: list[str] = field(default_factory=list)
def __post_init__(self) -> None:
if not (1 <= self.port <= 65535):
raise ValueError(f"无效端口: {self.port}")
异步模式
import asyncio
import httpx
async def fetch_all(urls: list[str]) -> list[bytes]:
"""并发获取多个 URL。"""
async with httpx.AsyncClient() as client:
tasks = [client.get(url) for url in urls]
responses = await asyncio.gather(*tasks)
return [r.content for r in responses]
pytest fixture 和 parametrize
import pytest
from pathlib import Path
@pytest.fixture
def config_file(tmp_path: Path) -> Path:
cfg = tmp_path / "config.txt"
cfg.write_text("host=localhost\nport=8080\n")
return cfg
@pytest.mark.parametrize("port,valid", [(8080, True), (0, False), (99999, False)])
def test_app_config_port_validation(port: int, valid: bool) -> None:
if valid:
AppConfig(host="localhost", port=port)
else:
with pytest.raises(ValueError):
AppConfig(host="localhost", port=port)
mypy 严格配置 (pyproject.toml)
[tool.mypy]
python_version = "3.11"
strict = true
warn_return_any = true
warn_unused_configs = true
disallow_untyped_defs = true
干净的 mypy --strict 输出如下:
Success: no issues found in 12 source files
任何报告的错误(例如 error: Function is missing a return type annotation)必须在实现被认为完成之前解决。
输出模板
在实现 Python 功能时,提供:
- 带有完整类型提示的模块文件
- 带有 pytest fixture 的测试文件
- 类型检查确认(mypy --strict 通过)
- 对所使用的 Pythonic 模式的简要说明
知识参考
Python 3.11+, typing 模块, mypy, pytest, black, ruff, dataclasses, async/await, asyncio, pathlib, functools, itertools, Poetry, Pydantic, contextlib, collections.abc, Protocol






