mcpField
P
python-dev

python-dev

github.com/databricks-solutions开发2.0k98 次安装2 天前更新
代码仓库

关于 python-dev

python-dev 是面向 Python 开发的技能,供编码 Agent 处理 Python 文件和 Jupyter notebook 时参考。它涵盖代码规范、pytest 测试及使用 uv 管理环境。

主要功能

  1. 01类型提示与 Google 风格文档字符串
  2. 02具体异常处理与输入验证
  3. 03基于 pytest 的测试与 TDD
  4. 04使用 uv 管理依赖和运行代码
  5. 05使用 Ruff 检查与格式化
  6. 06使用 Pyright 检查类型

适用场景

  1. 01编写或修改 Python 代码
  2. 02创建或更新 Jupyter notebook
  3. 03配置 Python 开发环境
  4. 04编写测试或审查代码质量

安装

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

$npx skills add https://github.com/databricks-solutions/ai-dev-kit --skill python-dev

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

详细介绍

Python 开发规则

概述

专注于代码质量、错误处理、测试和环境管理的 Python 开发指南。适用于处理 Python 代码或 Jupyter 笔记本。

何时使用此技能

在以下情况下使用此技能:

  • 编写新的 Python 代码或修改现有 Python 文件
  • 创建或更新 Jupyter 笔记本
  • 设置 Python 开发环境
  • 编写或更新测试
  • 审查 Python 代码的质量和最佳实践

代码质量

原则
  • DRY(不要重复自己):避免代码重复
  • 组合优于继承:优先采用组合模式
  • 尽可能使用纯函数:不产生副作用的函数
  • 简单方案优于巧妙方案:优先考虑可读性和可维护性
  • 优先针对常见用例设计:先解决主要问题,再处理边缘情况
风格与文档
  • 必须提供类型提示:所有函数都必须包含类型注解
  • 使用 snake_case 命名:变量、函数和模块均使用 snake_case
  • 使用 Google 风格的文档字符串:使用 Google 风格的文档字符串记录函数、类和模块
  • 保持函数简短:遵循单一职责原则——一个函数,一个用途
  • 保留现有注释:维护并更新现有代码注释
示例
def calculate_total(items: list[dict[str, float]], tax_rate: float = 0.08) -> float:
    """Calculate total cost including tax.
    
    Args:
        items: List of items with 'price' key
        tax_rate: Tax rate as decimal (default 0.08)
        
    Returns:
        Total cost including tax
        
    Raises:
        ValueError: If tax_rate is negative or items list is empty
    """
    if not items:
        raise ValueError("Items list cannot be empty")
    if tax_rate < 0:
        raise ValueError("Tax rate cannot be negative")
    
    subtotal = sum(item['price'] for item in items)
    return subtotal * (1 + tax_rate)

错误处理与效率

错误处理
  • 指定具体异常类型:捕获具体异常,不要使用裸 except
  • 尽早验证输入:在函数入口处检查输入
  • 不要使用裸 except:始终指定异常类型
效率模式
  • f-strings:使用 f-strings 格式化字符串
  • 推导式:适当情况下,优先使用列表/字典/集合推导式,而非循环
  • 上下文管理器:使用 with 语句管理资源
示例
def process_file(file_path: str) -> list[str]:
    """Process file and return lines.
    
    Args:
        file_path: Path to file
        
    Returns:
        List of non-empty lines
        
    Raises:
        FileNotFoundError: If file doesn't exist
        PermissionError: If file cannot be read
    """
    if not file_path:
        raise ValueError("File path cannot be empty")
    
    try:
        with open(file_path, 'r', encoding='utf-8') as f:
            return [line.strip() for line in f if line.strip()]
    except FileNotFoundError:
        raise FileNotFoundError(f"File not found: {file_path}")
    except PermissionError:
        raise PermissionError(f"Permission denied: {file_path}")

测试(关键)

框架与结构
  • 仅使用 pytest:只使用 pytest(不使用 unittest)
  • 测试位置:所有测试均放在 ./tests/ 目录中
  • 测试包:在 tests 目录中包含 __init__.py
  • TDD 方法:为所有新增或修改的代码编写/更新测试
  • 所有测试都必须通过:确保任务完成前所有测试均通过
测试结构示例
project/
├── src/
│   └── my_module.py
└── tests/
    ├── __init__.py
    └── test_my_module.py
测试示例
# tests/test_calculations.py
import pytest
from src.calculations import calculate_total

def test_calculate_total_basic():
    """Test basic total calculation."""
    items = [{'price': 10.0}, {'price': 20.0}]
    result = calculate_total(items, tax_rate=0.1)
    assert result == 33.0

def test_calculate_total_empty_list():
    """Test error handling for empty list."""
    with pytest.raises(ValueError, match="Items list cannot be empty"):
        calculate_total([])

def test_calculate_total_negative_tax():
    """Test error handling for negative tax rate."""
    items = [{'price': 10.0}]
    with pytest.raises(ValueError, match="Tax rate cannot be negative"):
        calculate_total(items, tax_rate=-0.1)

环境管理

依赖管理
  • 仅使用 uv:所有打包、环境和脚本执行均通过 uv 完成
  • 不使用 pip/venv/conda:不要使用 pip、python3 -m venv 或 conda——这些都由 uv 处理
  • 以 pyproject.toml 为准:在 pyproject.toml 中定义所有依赖(而不是 requirements.txt)
环境设置示例
# Install dependencies from pyproject.toml
uv sync

# Install with optional dev dependencies
uv sync --extra dev

# Run a script (no activation needed)
uv run python script.py

# Run pytest
uv run pytest

# Add a new dependency
uv add requests

# Remove a dependency
uv remove requests
运行 Python 代码
  • 使用 uv run 执行脚本——无需手动激活虚拟环境
  • 使用 uv run <tool> 运行开发工具(pytest、ruff 等)
  • 依赖定义在 pyproject.toml 中(而非 requirements.txt)
代码检查与格式化(Ruff)
  • Ruff:使用 Ruff 进行代码检查和格式化(替代 flake8、black、isort)
# Lint code
uv run ruff check .

# Lint and auto-fix
uv run ruff check --fix .

# Format code
uv run ruff format .

# Check formatting without changes
uv run ruff format --check .
类型检查(Pyright)
# Check types
uv run pyright

注意:使用 pyright 进行类型检查——不要使用 mypy。

最佳实践总结

  1. 代码质量:DRY、组合、纯函数、简单方案
  2. 风格:类型提示、snake_case、Google 风格文档字符串、简短函数
  3. 错误:具体异常、尽早验证、不使用裸 except
  4. 效率:f-strings、推导式、上下文管理器
  5. 测试:仅使用 pytest、TDD、测试放在 ./tests/ 中、所有测试都必须通过
  6. 环境:仅使用 uv 管理依赖和执行,使用 Ruff 进行代码检查和格式化,使用 Pyright 进行类型检查

评论

支持 Markdown