AgentSkillsCN

code-review

为已生成的Python脚本制定审查清单与常见模式。当被要求审查代码质量、查找Bug,或验证脚本时,可使用此功能。

SKILL.md
--- frontmatter
name: code-review
description: Checklist and patterns for reviewing generated Python scripts. Use this when asked to review code quality, find bugs, or validate scripts.

Code Review Skill: Python Quality Checklist

Overview

This skill provides a systematic approach to reviewing Python scripts generated by agents, ensuring they meet production quality standards.

Review Checklist

1. Imports & Structure

  • All imports at top of file
  • Standard library → third-party → local imports order
  • No unused imports
  • No circular imports
  • if __name__ == "__main__": guard present

2. Error Handling

  • File operations wrapped in try/except
  • Network requests have timeout and retry logic
  • Meaningful error messages
  • Graceful degradation (script doesn't crash silently)
python
# ❌ Bad
data = json.load(open('file.json'))

# ✅ Good
try:
    with open('file.json', 'r', encoding='utf-8') as f:
        data = json.load(f)
except FileNotFoundError:
    print("Error: file.json not found")
    sys.exit(1)
except json.JSONDecodeError as e:
    print(f"Error: Invalid JSON - {e}")
    sys.exit(1)

3. Type Hints & Documentation

  • Function signatures have type hints
  • Module has docstring explaining purpose
  • Complex logic has inline comments
  • Public functions have docstrings
python
# ✅ Good
def analyze_volatility(coins: list[dict]) -> dict:
    """
    Generate volatility statistics from coin data.
    
    Args:
        coins: List of coin dictionaries with price_change_percentage_24h
        
    Returns:
        Dictionary with statistics including top gainer/loser
    """

4. File I/O Best Practices

  • Always specify encoding='utf-8'
  • Use context managers (with statements)
  • Close resources explicitly or use context managers
  • Use relative paths or make paths configurable
python
# ❌ Bad
f = open('output.txt', 'w')
f.write(data)
f.close()

# ✅ Good
with open('output.txt', 'w', encoding='utf-8') as f:
    f.write(data)

5. Data Validation

  • Validate JSON structure before processing
  • Handle empty arrays/missing keys
  • Check for None/null values
  • Validate numeric ranges
python
# ✅ Good
def safe_get_change(coin: dict) -> float:
    """Safely extract price change, defaulting to 0."""
    change = coin.get('price_change_percentage_24h')
    return float(change) if change is not None else 0.0

6. Visualization Scripts

  • Figure size appropriate for content
  • Labels and titles on all axes
  • Legend present if multiple series
  • plt.tight_layout() called
  • plt.savefig() with explicit dpi
  • plt.close() after saving (prevent memory leaks)

Common Anti-Patterns

Anti-PatternProblemFix
Bare except:Catches all errors including KeyboardInterruptSpecify exception types
Hardcoded pathsBreaks on other machinesUse os.path or pathlib
No encodingFails on non-ASCII dataAlways specify encoding='utf-8'
print() for errorsLost in stdoutUse logging or sys.stderr
Magic numbersUnclear meaningDefine as named constants

Validation Commands

bash
# Syntax check
python -m py_compile script.py

# Type checking (if mypy installed)
mypy script.py

# Linting (if flake8 installed)
flake8 script.py

# Run and capture all output
python script.py 2>&1

# Check for undefined names
python -c "import ast; ast.parse(open('script.py').read())"

Severity Levels

LevelActionExamples
🔴 CriticalMust fixSyntax errors, unhandled exceptions, data loss
🟠 WarningShould fixMissing error handling, no encoding specified
🟡 SuggestionNice to haveMissing docstrings, could use type hints