mcpField
P
python-pro

python-pro

github.com/jeffallan开发12.1k8.9k 次安装今天更新
代码仓库

关于 python-pro

面向 Python 3.11 及更高版本开发者的编程技能,侧重类型安全和异步优先的代码,涵盖 pytest 测试及严格类型检查与代码规范验证。

主要功能

  1. 01完整类型注解与严格 mypy
  2. 02异步 I/O 实现模式
  3. 03pytest 固件与测试指导
  4. 04Pythonic 设计与错误处理
  5. 05Poetry 打包指导
  6. 06black 与 ruff 验证

适用场景

  1. 01编写类型安全的 Python API
  2. 02实现异步 I/O 操作
  3. 03使用固件构建 pytest 测试套件
  4. 04通过 Poetry 打包项目

安装

复制下面的命令,在终端中运行。

$npx skills add https://github.com/jeffallan/claude-skills --skill python-pro

安装后在 Claude Code 中输入/python-pro确认已加载。

包含的文件

除 SKILL.md 外,安装时一起下载的参考资料和脚本。

references/
async-patterns.md
packaging.md
standard-library.md
testing.md
type-system.md

详细介绍

Python 专家

专注于 Python 3.11+ 的现代实践,侧重类型安全、异步优先和生产就绪的代码。

何时使用此技能

  • 编写类型安全且类型覆盖完整的 Python 代码
  • 为 I/O 操作实现 async/await 模式
  • 使用 fixture 和模拟设置 pytest 测试套件
  • 使用推导式、生成器和上下文管理器编写符合 Python 风格的代码
  • 使用 Poetry 构建软件包并采用合适的项目结构
  • 优化性能并进行性能分析

核心工作流

  1. 分析代码库 — 检查项目结构、依赖项、类型覆盖率和测试套件
  2. 设计接口 — 定义协议、数据类和类型别名
  3. 实现 — 编写带有完整类型提示和错误处理的 Python 风格代码
  4. 测试 — 创建全面的 pytest 测试套件,覆盖率超过 90%
  5. 验证 — 运行 mypy --strict、black、ruff
    • 如果 mypy 失败:修复报告的类型错误,并在继续之前重新运行
    • 如果测试失败:调试断言、更新 fixture,并反复迭代直至全部通过
    • 如果 ruff/black 报告问题:应用自动修复,然后重新验证

参考指南

根据上下文加载详细指南:

主题参考资料加载时机
类型系统references/type-system.md类型提示、mypy、泛型、Protocol
异步模式references/async-patterns.mdasync/await、asyncio、任务组
标准库references/standard-library.mdpathlib、dataclasses、functools、itertools
测试references/testing.mdpytest、fixture、模拟、parametrize
打包references/packaging.mdpoetry、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]:
    """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
带验证的数据类
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]
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 功能时,请提供:

  1. 包含完整类型提示的模块文件
  2. 带有 pytest fixture 的测试文件
  3. 类型检查确认(mypy --strict 通过)
  4. 对所用 Python 风格模式的简要说明

知识参考

Python 3.11+、typing 模块、mypy、pytest、black、ruff、dataclasses、async/await、asyncio、pathlib、functools、itertools、Poetry、Pydantic、contextlib、collections.abc、Protocol

由 @jeffallan 维护,他是 Synergetic Solutions 的首席顾问。

文档

评论

支持 Markdown