一键导入
refactor-code
Modernize legacy Python code with type hints and efficient patterns. Use when asked to refactor, modernize, or update Python code.
用 Codex 或 Claude 帮你安装 复制这段 Prompt,粘贴到 Codex、Claude 或其他助手里,让它检查 Skill 页面并帮你完成安装。
菜单
Modernize legacy Python code with type hints and efficient patterns. Use when asked to refactor, modernize, or update Python code.
用 Codex 或 Claude 帮你安装 复制这段 Prompt,粘贴到 Codex、Claude 或其他助手里,让它检查 Skill 页面并帮你完成安装。
基于 SOC 职业分类
Rewrite technical documents, guides, notes, RFCs, and tutorials into beginner-friendly blog posts with simple explanations and practical examples. Use when the user wants to transform technical content into a blog post, simplify documentation, or write a tutorial from reference material.
Codebase cleanup workflow for applying YAGNI, DRY, and KISS principles. Use when asked to review, simplify, refactor, or clean up a project for unnecessary code, duplicated logic, over-abstraction, excessive complexity, stale tests, or docs that no longer match implementation.
Debug errors, failed commands, test failures, runtime exceptions, wrong output, flaky behavior, regressions, config/import issues, and bug-fix requests using a local-first CLI workflow with Context7, GitHub CLI, and the Web Search MCP for external evidence.
Automatically transcribes, structures, and compiles images or text drafts into professional, print-ready vector A4 PDFs using WeasyPrint. Universal - handles any content type: badges, code blocks, tables, blockquotes, RTL text, images, and more.
Research any topic — current events, products, people, concepts, comparisons — using Web Search MCP for evidence gathering and structured multi-source synthesis.
Final-gate review of completed code changes using a systematic verification approach. Use when the user asks to "review my code", "check my changes", or after a cleanup, refactor, feature, or fix.
| name | refactor-code |
| description | Modernize legacy Python code with type hints and efficient patterns. Use when asked to refactor, modernize, or update Python code. |
Prune with the
cleanup-codeagent before refactoring. Refactor code that should exist — not code that should be deleted. Cleanup first, refactor second.
Transform legacy Python code into maintainable, efficient implementations.
pyproject.toml, setup.cfg, .python-version, or CI config (e.g., python-version matrix in .github/workflows/). Only apply features available at or below that floor — do not use match statements on a 3.9 codebase, tomllib below 3.11, etc.Skip updates if:
Modernize to reduce noise, improve safety, or clarify intent.
pyupgrade, ruff --fix, or python-modernize — for bulk transformations. Reserve manual refactoring for structural changes (dataclasses, match, async patterns, type hints).Section 1: Type System
TypedDict or dataclassesSection 2: Syntax Modernization
% and .format() string formatting with f-stringsos.path.* path operations with pathlibconfigparser with tomllib (3.11+) or tomli where appropriateif/elif chains over a single variable with match statements (Python 3.10+ only)Section 3: Structural Improvements
@dataclass__init__, __repr__, __eq__) where dataclass covers them__slots__ to hot-path dataclasses where memory efficiency mattersenumerate, list/dict/set comprehensions, zipexcept: or except Exception: without re-raise with specific exception typesprint statements with logging calls at appropriate levelsAsync (if applicable)
asyncio patterns — no sync blocking calls (e.g., time.sleep, open()) inside async functionsasync with and async for where available on async-capable resourcesasyncio.gather() for concurrent independent tasks instead of sequential await callsasyncio.sleep(0) busy-loops with proper event-driven patternsImports
For detailed tool commands, see CLAUDE.md if present in the project root; otherwise use the defaults below.
Run type checking, linting, and tests to establish baseline (from project root; use uv run when pyproject.toml exists):
uv run mypy src/
uv run ruff check .
uv run pytest --tb=short
uv run pytest --cov=src --cov-report=term-missing
If the project has no uv/pyproject.toml, use commands from the project README instead.
Record the baseline pass/fail counts. Flag existing test failures; do not treat them as regressions.
Verify refactored code passes all checks:
# Before
msg = "Host %s unreachable after %d retries" % (host, retries)
msg = "Host {} unreachable after {} retries".format(host, retries)
# After
msg = f"Host {host} unreachable after {retries} retries"
# Preserve alignment options where needed
msg = f"{'Interface':<20} {'Status':>10}"
# Before
class DeviceInfo:
def __init__(self, hostname, ip, platform):
self.hostname = hostname
self.ip = ip
self.platform = platform
def __repr__(self):
return f"DeviceInfo({self.hostname}, {self.ip}, {self.platform})"
# After
from dataclasses import dataclass
@dataclass
class DeviceInfo:
hostname: str
ip: str
platform: str
# Before
import os
config_path = os.path.join(base_dir, "config", "devices.yaml")
if os.path.exists(config_path):
with open(config_path) as f:
...
# After
from pathlib import Path
config_path = Path(base_dir) / "config" / "devices.yaml"
if config_path.exists():
with config_path.open() as f:
...
# Before
if platform == "ios":
driver = IOSDriver()
elif platform == "eos":
driver = EOSDriver()
elif platform == "nxos":
driver = NXOSDriver()
else:
raise ValueError(f"Unknown platform: {platform}")
# After (Python 3.10+)
match platform:
case "ios":
driver = IOSDriver()
case "eos":
driver = EOSDriver()
case "nxos":
driver = NXOSDriver()
case _:
raise ValueError(f"Unknown platform: {platform}")
# Before
print(f"Connecting to {host}...")
print(f"ERROR: timeout on {host}")
# After
import logging
logger = logging.getLogger(__name__)
logger.debug("Connecting to %s", host)
logger.error("Timeout on %s", host)
Why
%-style args in logging, not f-strings? The logging module uses lazy formatting — the string is only interpolated if the log level is actually active. With f-strings, the interpolation happens unconditionally at the call site, even if the message is never emitted. Use%-style positional args ("msg %s", value) in alllogger.*calls.
Modernize legacy Python code after pruning with the cleanup-code agent.
rules/python-style.md — Toolchain, typing, security scanscleanup-code agent — Run this first to prune dead code before refactoringreview-code skill — For final gate review after refactoring