python-pro

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Python Pro

Python Pro

Modern Python 3.11+ specialist focused on type-safe, async-first, production-ready code.
专注于现代Python 3.11+的开发专家,主打类型安全、异步优先、可用于生产环境的代码。

When to Use This Skill

何时使用该技能

  • Writing type-safe Python with complete type coverage
  • Implementing async/await patterns for I/O operations
  • Setting up pytest test suites with fixtures and mocking
  • Creating Pythonic code with comprehensions, generators, context managers
  • Building packages with Poetry and proper project structure
  • Performance optimization and profiling
  • 编写具有完整类型覆盖的类型安全Python代码
  • 为I/O操作实现async/await模式
  • 搭建包含fixture和mock的pytest测试套件
  • 使用推导式、生成器、上下文管理器编写符合Python风格的代码
  • 用Poetry构建包并规划合理的项目结构
  • 性能优化与性能分析

Core Workflow

核心工作流程

  1. Analyze codebase — Review structure, dependencies, type coverage, test suite
  2. Design interfaces — Define protocols, dataclasses, type aliases
  3. Implement — Write Pythonic code with full type hints and error handling
  4. Test — Create comprehensive pytest suite with >90% coverage
  5. Validate — Run
    mypy --strict
    ,
    black
    ,
    ruff
    • If mypy fails: fix type errors reported and re-run before proceeding
    • If tests fail: debug assertions, update fixtures, and iterate until green
    • If ruff/black reports issues: apply auto-fixes, then re-validate
  1. 分析代码库 — 审查结构、依赖、类型覆盖情况和测试套件
  2. 设计接口 — 定义协议(Protocol)、数据类(dataclasses)、类型别名
  3. 实现代码 — 编写带有完整类型提示和错误处理的Python风格代码
  4. 测试 — 创建覆盖率超过90%的全面pytest测试套件
  5. 验证 — 运行
    mypy --strict
    、
    black
    、
    ruff
    • 若mypy检查失败:修复报告的类型错误后重新运行
    • 若测试失败:调试断言、更新fixture,迭代直至测试通过
    • 若ruff/black报告问题:应用自动修复,然后重新验证

Reference Guide

参考指南

Load detailed guidance based on context:
TopicReferenceLoad When
Type System
references/type-system.md
Type hints, mypy, generics, Protocol
Async Patterns
references/async-patterns.md
async/await, asyncio, task groups
Standard Library
references/standard-library.md
pathlib, dataclasses, functools, itertools
Testing
references/testing.md
pytest, fixtures, mocking, parametrize
Packaging
references/packaging.md
poetry, pip, pyproject.toml, distribution
根据上下文加载详细指导:
主题参考文档加载场景
类型系统
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、参数化
打包
references/packaging.md
poetry、pip、pyproject.toml、分发

Constraints

约束条件

MUST DO

必须遵守

  • Type hints for all function signatures and class attributes
  • PEP 8 compliance with black formatting
  • Comprehensive docstrings (Google style)
  • Test coverage exceeding 90% with pytest
  • Use
    X | None
    instead of
    Optional[X]
    (Python 3.10+)
  • Async/await for I/O-bound operations
  • Dataclasses over manual init methods
  • Context managers for resource handling
  • 所有函数签名和类属性都要有类型提示
  • 遵循PEP 8规范,使用black格式化代码
  • 编写全面的文档字符串(Google风格)
  • 使用pytest实现测试覆盖率超过90%
  • 使用
    X | None
    替代
    Optional[X]
    (Python 3.10+)
  • 针对I/O密集型操作使用async/await
  • 使用dataclasses替代手动编写__init__方法
  • 使用上下文管理器处理资源

MUST NOT DO

禁止操作

  • Skip type annotations on public APIs
  • Use mutable default arguments
  • Mix sync and async code improperly
  • Ignore mypy errors in strict mode
  • Use bare except clauses
  • Hardcode secrets or configuration
  • Use deprecated stdlib modules (use pathlib not os.path)
  • 公共API跳过类型注解
  • 使用可变默认参数
  • 不当混合同步和异步代码
  • 忽略mypy严格模式下的错误
  • 使用裸except子句
  • 硬编码密钥或配置信息
  • 使用已废弃的标准库模块(用pathlib替代os.path)

Code Examples

代码示例

Type-annotated function with error handling

带错误处理的类型注解函数

python
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
python
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 with validation

带验证的数据类

python
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}")
python
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}")

Async pattern

异步模式示例

python
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]
python
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 and parametrize

pytest fixture与参数化示例

python
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)
python
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 strict configuration (pyproject.toml)

mypy严格模式配置(pyproject.toml)

toml
[tool.mypy]
python_version = "3.11"
strict = true
warn_return_any = true
warn_unused_configs = true
disallow_untyped_defs = true
Clean
mypy --strict
output looks like:
Success: no issues found in 12 source files
Any reported error (e.g.,
error: Function is missing a return type annotation
) must be resolved before the implementation is considered complete.
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
)必须在完成实现前解决。

Output Templates

输出模板

When implementing Python features, provide:
  1. Module file with complete type hints
  2. Test file with pytest fixtures
  3. Type checking confirmation (mypy --strict passes)
  4. Brief explanation of Pythonic patterns used
实现Python功能时,需提供:
  1. 带有完整类型提示的模块文件
  2. 包含pytest fixture的测试文件
  3. 类型检查确认(mypy --strict通过)
  4. 对所用Python风格模式的简要说明

Knowledge Reference

知识参考

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