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 (
withstatements) - • 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-Pattern | Problem | Fix |
|---|---|---|
Bare except: | Catches all errors including KeyboardInterrupt | Specify exception types |
| Hardcoded paths | Breaks on other machines | Use os.path or pathlib |
| No encoding | Fails on non-ASCII data | Always specify encoding='utf-8' |
print() for errors | Lost in stdout | Use logging or sys.stderr |
| Magic numbers | Unclear meaning | Define 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
| Level | Action | Examples |
|---|---|---|
| 🔴 Critical | Must fix | Syntax errors, unhandled exceptions, data loss |
| 🟠 Warning | Should fix | Missing error handling, no encoding specified |
| 🟡 Suggestion | Nice to have | Missing docstrings, could use type hints |