python-dev

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Python Development Rules

Python开发规则

Overview

概述

Python development guidance focused on code quality, error handling, testing, and environment management. Apply when working with Python code or Jupyter notebooks.
本Python开发指导聚焦于代码质量、错误处理、测试和环境管理。适用于处理Python代码或Jupyter笔记本时遵循。

When to Use This Skill

何时使用本技能

Use this skill when:
  • Writing new Python code or modifying existing Python files
  • Creating or updating Jupyter notebooks
  • Setting up Python development environments
  • Writing or updating tests
  • Reviewing Python code for quality and best practices
在以下场景使用本技能:
  • 编写新的Python代码或修改现有Python文件
  • 创建或更新Jupyter笔记本
  • 搭建Python开发环境
  • 编写或更新测试用例
  • 评审Python代码的质量与最佳实践

Code Quality

代码质量

Principles

原则

  • DRY (Don't Repeat Yourself): Avoid code duplication
  • Composition over inheritance: Prefer composition patterns
  • Pure functions when possible: Functions without side effects
  • Simple solutions over clever ones: Prioritize readability and maintainability
  • Design for common use cases first: Solve the primary problem before edge cases
  • DRY(Don't Repeat Yourself,不要重复自己):避免代码重复
  • 组合优于继承:优先使用组合模式
  • 尽可能使用纯函数:无副作用的函数
  • 简洁方案优于巧妙方案:优先考虑可读性和可维护性
  • 先为常见用例设计:先解决核心问题,再处理边缘情况

Style & Documentation

风格与文档

  • Type hints required: All functions must include type annotations
  • snake_case naming: Use snake_case for variables, functions, and modules
  • Google-style docstrings: Document functions, classes, and modules using Google-style docstrings
  • Keep functions small: Single responsibility principle - one function, one purpose
  • Preserve existing comments: Maintain and update existing code comments
  • 必须添加类型提示:所有函数都必须包含类型注解
  • snake_case命名法:变量、函数和模块使用snake_case命名
  • Google风格文档字符串:使用Google风格的文档字符串为函数、类和模块编写文档
  • 保持函数精简:单一职责原则——一个函数只实现一个功能
  • 保留现有注释:维护并更新现有代码注释

Example

示例

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

Error Handling & Efficiency

错误处理与效率

Error Handling

错误处理

  • Specific exception types: Catch specific exceptions, not bare
    except
  • Validate inputs early: Check inputs at function entry
  • No bare except: Always specify exception types
  • 捕获特定异常类型:捕获特定的异常,不要使用裸
    except
  • 尽早验证输入:在函数入口处检查输入
  • 禁止裸except:始终指定异常类型

Efficiency Patterns

效率模式

  • f-strings: Use f-strings for string formatting
  • Comprehensions: Prefer list/dict/set comprehensions over loops when appropriate
  • Context managers: Use
    with
    statements for resource management
  • f-strings:使用f-strings进行字符串格式化
  • 推导式:在合适的情况下,优先使用列表/字典/集合推导式而非循环
  • 上下文管理器:使用
    with
    语句进行资源管理

Example

示例

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

Testing (Critical)

测试(至关重要)

Framework & Structure

框架与结构

  • pytest only: Use pytest exclusively (no unittest)
  • Test location: All tests in
    ./tests/
    directory
  • Test package: Include
    __init__.py
    in tests directory
  • TDD approach: Write/update tests for all new/modified code
  • All tests must pass: Ensure all tests pass before task completion
  • 仅使用pytest:仅使用pytest框架(不使用unittest)
  • 测试位置:所有测试用例放在
    ./tests/
    目录下
  • 测试包:在测试目录中包含
    __init__.py
    文件
  • TDD方法:为所有新增/修改的代码编写/更新测试用例
  • 所有测试必须通过:任务完成前确保所有测试用例通过

Test Structure Example

测试结构示例

project/
├── src/
│   └── my_module.py
└── tests/
    ├── __init__.py
    └── test_my_module.py
project/
├── src/
│   └── my_module.py
└── tests/
    ├── __init__.py
    └── test_my_module.py

Example Test

测试示例

python
undefined
python
undefined

tests/test_calculations.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)
undefined
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)
undefined

Environment Management

环境管理

Dependency Management

依赖管理

  • Use uv: Dependency management via uv
  • Virtual environments: Use virtual environments (
    venv
    ) or
    uv
  • Check existing venv: Always check for existing
    .venv
    in current or parent directories before creating new one
  • Activate before use: Activate
    .venv
    before installing packages or executing scripts
  • 使用uv:通过uv进行依赖管理
  • 虚拟环境:使用虚拟环境(
    venv
    )或
    uv
  • 检查现有虚拟环境:创建新虚拟环境前,务必检查当前目录或父目录中是否存在已有的
    .venv
  • 使用前激活:安装包或执行脚本前,激活
    .venv

Code Style

代码风格

  • Ruff: Use Ruff for code style consistency and linting
  • Ruff:使用Ruff保证代码风格一致性并进行代码检查

Environment Setup Example

环境搭建示例

bash
undefined
bash
undefined

Check for existing .venv

Check for existing .venv

if [ -d ".venv" ]; then source .venv/bin/activate elif [ -d "../.venv" ]; then source ../.venv/bin/activate else # Create new venv or use uv python3 -m venv .venv source .venv/bin/activate fi
if [ -d ".venv" ]; then source .venv/bin/activate elif [ -d "../.venv" ]; then source ../.venv/bin/activate else # Create new venv or use uv python3 -m venv .venv source .venv/bin/activate fi

Install dependencies

Install dependencies

pip install -r requirements.txt
pip install -r requirements.txt

Or with uv

Or with uv

uv pip install -r requirements.txt
undefined
uv pip install -r requirements.txt
undefined

Python Script Execution

Python脚本执行

  • Always activate virtual environment before running Python scripts
  • Use
    python3
    explicitly when not in venv
  • Check for
    requirements.txt
    or
    pyproject.toml
    for dependencies
  • 运行Python脚本前,务必激活虚拟环境
  • 未在虚拟环境中时,显式使用
    python3
  • 检查是否存在
    requirements.txt
    pyproject.toml
    以获取依赖信息

Best Practices Summary

最佳实践总结

  1. Code Quality: DRY, composition, pure functions, simple solutions
  2. Style: Type hints, snake_case, Google docstrings, small functions
  3. Errors: Specific exceptions, early validation, no bare except
  4. Efficiency: f-strings, comprehensions, context managers
  5. Testing: pytest only, TDD, tests in
    ./tests/
    , all must pass
  6. Environment: uv or venv, check existing
    .venv
    , activate before use, Ruff for style
  1. 代码质量:DRY原则、组合模式、纯函数、简洁方案
  2. 风格规范:类型提示、snake_case命名、Google文档字符串、精简函数
  3. 错误处理:特定异常、尽早验证、禁止裸except
  4. 效率优化:f-strings、推导式、上下文管理器
  5. 测试规范:仅使用pytest、TDD方法、测试用例放在
    ./tests/
    、所有测试必须通过
  6. 环境管理:使用uv或venv、检查现有
    .venv
    、使用前激活、用Ruff保证风格