python-pro
Use when building Python 3.11+ applications requiring type safety, async programming, or robust error handling. Generates type-annotated Python code, configures mypy in strict mode, writes pytest test suites with fixtures and mocking, and validates code with black and ruff. Invoke for type hints, async/await patterns, dataclasses, dependency injection, logging configuration, and structured error handling.
- License 许可
- MIT
- 最近更新
- 2026-06-29
- Stars
- ★ 0
- Forks
- 0
01 前言 Front Matter
- name
- python-pro
- license
- MIT
- metadata
- { "role": "specialist", "scope": "implementation", "author": "https://github.com/Jeffallan", "domain": "language", "version": "1.1.0", "triggers": "Python development, type hints, async Python, pytest, mypy, dataclasses, Python best practices, Pythonic code", "output-format": "code", "related-skills": "fastapi-expert, devops-engineer" }
- description
- Use when building Python 3.11+ applications requiring type safety, async programming, or robust error handling. Generates type-annotated Python code, configures mypy in strict mode, writes pytest test suites with fixtures and mocking, and validates code with black and ruff. Invoke for type hints, async/await patterns, dataclasses, dependency injection, logging configuration, and structured error handling.
02 资源文件 4
- 参考文档references/async-patterns.md9.1 KB
- 参考文档references/packaging.md9.4 KB
- 参考文档references/standard-library.md8.9 KB
- 参考文档references/type-system.md6.5 KB
03 SKILL.md 正文
Python Pro
现代 Python 3.11+ 专家,专注于类型安全、异步优先、生产就绪的代码。
何时使用此 Skill
- 编写具有完整类型覆盖的类型安全 Python 代码
- 为 I/O 操作实现 async/await 模式
- 使用 pytest 设置包含 fixtures 和 mocking 的测试套件
- 使用推导式、生成器、上下文管理器编写 Pythonic 代码
- 使用 Poetry 和合理的项目结构构建包
- 性能优化和分析
核心工作流程
- 分析代码库 — 审查结构、依赖项、类型覆盖、测试套件
- 设计接口 — 定义 Protocol、dataclasses、类型别名
- 实现 — 编写带有完整类型提示和错误处理的 Pythonic 代码
- 测试 — 创建覆盖率达 80%+ 的全面 pytest 套件
- 验证 — 运行
mypy --strict、black、ruff- 如果 mypy 失败:修复报告的类型错误并重新运行,然后继续
- 如果测试失败:调试断言、更新 fixtures,迭代直至全部通过
- 如果 ruff/black 报告问题:应用自动修复,然后重新验证
参考指南
根据上下文加载详细指导:
| 主题 | 参考文档 | 加载时机 |
|---|---|---|
| 类型系统 | references/type-system.md |
类型提示、mypy、泛型、Protocol |
| 异步模式 | references/async-patterns.md |
async/await、asyncio、任务组 |
| 标准库 | references/standard-library.md |
pathlib、dataclasses、functools、itertools |
| 测试 | 参见 python-testing skill |
pytest fixtures、mocking、parametrize |
| 打包 | references/packaging.md |
poetry、pip、pyproject.toml、分发 |
约束
必须做
- 所有函数签名和类属性都需要类型提示
- 符合 PEP 8 规范的 black 格式化
- 完善的文档字符串(Google 风格)
- 使用 pytest 实现超过 80% 的测试覆盖率
- 使用
X | None代替Optional[X](Python 3.10+) - 对 I/O 密集型操作使用 async/await
- 使用 Dataclasses 代替手写 init 方法
- 使用上下文管理器处理资源
禁止做
- 在公共 API 上跳过类型注解
- 使用可变的默认参数
- 不当混用同步和异步代码
- 在 strict 模式下忽略 mypy 错误
- 使用裸 except 子句
- 硬编码密钥或配置
- 使用已弃用的 stdlib 模块(使用 pathlib 而非 os.path)
代码示例
带错误处理的类型注解函数
from pathlib import Path
def read_config(path: Path) -> dict[str, str]:
"""Read configuration from a file.
Args:
path: Path to the configuration file.
Returns:
Parsed key-value configuration entries.
Raises:
FileNotFoundError: If the config file does not exist.
ValueError: If a line cannot be parsed.
"""
config: dict[str, str] = {}
with path.open() as f:
for line in f:
key, _, value = line.partition("=")
if not key.strip():
raise ValueError(f"Invalid config line: {line!r}")
config[key.strip()] = value.strip()
return config
带验证的 Dataclass
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"Invalid port: {self.port}")
异步模式
import asyncio
import httpx
async def fetch_all(urls: list[str]) -> list[bytes]:
"""Fetch multiple URLs concurrently."""
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]
mypy strict 配置 (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 fixtures 的测试文件
- 类型检查确认(mypy --strict 通过)
- 对所使用的 Pythonic 模式的简要说明
知识参考
Python 3.11+、typing 模块、mypy、pytest、black、ruff、dataclasses、async/await、asyncio、pathlib、functools、itertools、Poetry、Pydantic、contextlib、collections.abc、Protocol
04 同仓库更多 Skills
websocket-engineer
当使用 WebSocket 或 Socket.IO 构建实时通信系统时使用。适用于双向消息通信、Redis 水平扩展、在线状态追踪、房间管理。
security-reviewer
识别安全漏洞,生成带有严重性评级的结构化审计报告,并提供可操作的安全修复建议。在开展安全审计、审查代码漏洞或分析基础设施安全时使用。适用于 SAST 扫描、渗透测试、DevSecOps 实践、云安全审查、依赖审计、密钥扫描或合规检查。生成漏洞报告、优先级建议和合规清单。
secure-code-guardian
用于实现认证/授权、保护用户输入或防御 OWASP Top 10 漏洞 —— 包括自定义安全实现,例如使用 bcrypt/argon2 哈希密码、使用参数化语句清理 SQL 查询、配置 CORS/CSP 头部、使用 Zod 验证输入以及设置 JWT token。适用于认证、授权、输入验证、加密、OWASP Top 10 防护、安全会话管理和安全加固。对于预构建的 OAuth/SSO 集成或独立的安全审计,请考虑使用更专业的 skill。
rust-engineer
编写、审查和调试符合 Rust 风格的代码,确保内存安全和零成本抽象。实现所有权模式、管理生命周期、设计 trait 层级、使用 tokio 构建异步应用程序,以及使用 Result/Option 结构化错误处理。适用于构建 Rust 应用程序、解决所有权或借用问题、设计基于 trait 的 API、实现 async/await 并发、创建 FFI 绑定,或优化性能和内存安全。触发词:Rust, Cargo, ownership, borrowing, lifetimes, async Rust, tokio, zero-cost abstractions, memory safety, systems programming。
react-native-expert
使用 React Native 和 Expo 构建、优化和调试跨平台移动应用。实现导航层级结构(标签页、堆栈、抽屉),配置原生模块,使用 memo 和 useCallback 优化 FlatList 渲染,处理 iOS 和 Android 的平台特定代码。在构建 React Native 或 Expo 移动应用、设置导航、集成原生模块、改善滚动性能、处理 SafeArea 或键盘输入、配置 Expo SDK 项目时使用。
react-expert
当你使用 .jsx 或 .tsx 文件构建 React 18+ 应用、Next.js App Router 项目或 create-react-app 时使用。创建组件、实现自定义 hooks、调试渲染问题、将类组件迁移为函数组件、以及实现状态管理。适用于 Server Components、Suspense 边界、useActionState 表单、性能优化或 React 19 特性。