Improves code quality through idiomatic refactoring while ensuring tests remain green.
Install
mkdir -p .claude/skills/refactor-project-stage-academy && curl -L -o skill.zip "https://agentskills.codes/api/skills/download/15628" && unzip -o skill.zip -d .claude/skills/refactor-project-stage-academy && rm skill.zipInstalls to .claude/skills/refactor-project-stage-academy
Activation
This is the description your AI agent reads to decide when to run this skill — the better it matches your request, the more reliably it fires.
Step 4 of TDD. Improve code readability and performance while maintaining green tests. Focus on O(n) complexity and idiomatic patterns. Use after tests pass.Key capabilities
- →Analyze code for O(n) complexity and optimize performance
- →Apply idiomatic Python patterns like list comprehensions and context managers
- →Ensure functions are small (<= 20 lines) and have a single responsibility
- →Verify refactoring changes by re-running the test suite and linters
- →Prefer early returns to reduce nesting in code
- →Ensure code compliance with `ruff` and `isort`
How it works
This skill refines passing code by analyzing complexity, applying idiomatic patterns, and enforcing clean code principles, with verification by the existing test suite and linters.
Inputs & outputs
When to use refactor
- →Optimizing code performance
- →Applying idiomatic patterns
- →Refactoring to clean code standards
- →Ensuring test-driven development compliance
About this skill
Refactor Skill (TDD Step 4)
This skill focuses on refining the passing implementation into its most readable, maintainable, and efficient form. All changes must be verified by the existing test suite.
Workflow
- Analyze Complexity: Identify O(n^2) or higher complexity and optimize for performance.
- Idiomatic Patterns: Apply Pythonic patterns (list comprehensions, context managers, structural pattern matching).
- Clean Code Check: Ensure functions are small (<= 20 lines) and have a single responsibility.
- Verification: Re-run the test suite and linters after each refactoring step.
Mandates
- Tests Must Remain Green: Refactoring only applies to internal logic; behavior must not change.
- Shortest Clear Path: Choose the most concise implementation that meets all readability and standard requirements.
- Early Returns: Prefer early returns to reduce nesting.
- Explicit Imports: Avoid wildcard imports or ambiguous names.
- Ruff Optimization: Ensure the code is fully compliant with
ruffandisort.
Common Mistakes
- Refactoring without Tests: Never attempt to refactor if you don't have passing tests.
- Behavioral Changes: If you need to change behavior, return to Step 1 (Plan).
- Over-abstraction: Avoid complex patterns that make the code harder to read than a simple implementation.
Canonical Example
# Before
async def fetch_all(self, items):
results = []
for item in items:
if item.is_valid:
results.append(item.data)
return results
# After
async def fetch_all(self, items: list[Item]) -> list[ItemData]:
"""Retrieves data for all valid items.
Args:
items: A list of Item objects to process.
Returns:
A list of ItemData for all valid items.
"""
return [item.data for item in items if item.is_valid]
Python Coding Standards
General
- Use type hints on every function signature and variable where the type is not obvious.
- Coding Style: PEP 8 enforced by
ruff. Max line length: 100. - Write docstrings on every public function and class using the Google-style format:
def my_function(arg: str) -> int: """Short one-line description of what the function does. Optional longer description if needed, explaining the logic and any non-obvious details and how function does what it does. Args: arg: What this argument represents. Returns: What the function returns. Raises: SomeError: When and why it is raised. """ - No inline comments unless they answer why the code is written this way (not what it does). Readable names make the "what" obvious.
- Prefer descriptive variable names over comments:
filtered_booksnotresult. - Follow all Clean Code principles: SOLID, DRY, small functions, clear names.
- Use
StrEnumfor enumerations that are also used as string values. - Use dataclasses for domain model objects, not
TypedDictor plain dicts. - Care about O(n) complexity of your code, especially in loops and recursive functions.
- Make code secure, modular and testable.
- Of all possible implementations that meet all other criteria mentioned in this instructions, choose the shortest, most concise and the most readable.
Clean code guide
Naming
- Names must reveal intent, not implementation.
- If a name needs a comment, rename it.
- One word per concept across the codebase (get ≠ fetch).
- Avoid abbreviations, encodings, prefixes, suffixes.
- Never use noise words:
data,info,manager,handler. - Prefer clarity over brevity.
- Name booleans this way:
is_,has_,can_
Functions
- Functions must be small (≤ 20 lines).
- A function must do exactly one thing.
- One abstraction level per function.
- Avoid deep nesting; extract functions instead.
- A function is either:
- a command (changes state)
- or a query (returns data)
- Never both.
Control Flow
- Prefer early returns.
- Avoid
elseafterreturn. - Large
if/elif/matchblocks indicate missing polymorphism. break/continueallowed only in small scopes.
Errors & Exceptions
- Use exceptions, never error codes.
- Never return
Noneto signal failure. - Exceptions must include:
- operation
- reason
- relevant context
- Error handling must never obscure main logic.
Comments
- Prefer expressive code over comments.
- Comments do NOT fix bad code.
- Allowed:
- intent
- warnings
- TODO (temporary only)
- Forbidden:
- redundant comments
- commented-out code
- historical logs
- obvious explanations
- If a comment explains logic → refactor the code.
Tests
- Tests are production code.
- Tests must be readable.
- One concept per test.
- Tests must be:
- Fast
- Independent
- Repeatable
- Self-validating
- Written before or with production code
Python-Specific Rules
- Prefer composition over inheritance.
- Use
withfor all resource management. - Avoid global mutable state.
- No magic numbers; name all constants.
- Explicit imports only.
- Avoid metaprogramming unless strictly required.
Other Rules
- Hard to name → redesign.
- Growing function → split.
- Comment explaining logic → refactor.
- Type checks → missing polymorphism.
- Many files touched per change → abstraction failure.
When not to use it
- →When refactoring without passing tests
- →When intending to change code behavior
- →When introducing complex patterns that reduce readability
Limitations
- →Tests must remain green after refactoring
- →Refactoring only applies to internal logic, not behavior changes
- →Over-abstraction that makes code harder to read should be avoided
How it compares
This skill provides a structured, test-driven approach to code refinement, ensuring that all changes improve code quality without altering behavior, unlike ad-hoc optimizations that might introduce regressions.
Compared to similar skills
refactor side by side with the closest alternatives in the catalog.
| Skill | Installs | Updated | Safety | Difficulty |
|---|---|---|---|---|
| refactor (this skill) | 0 | 5mo | No flags | Intermediate |
| clojure-write | 16 | 3mo | No flags | Intermediate |
| add-uint-support | 18 | 9mo | No flags | Intermediate |
| python-design-patterns | 19 | 2mo | No flags | Intermediate |
Try saying
Example prompts that trigger this skill in your AI assistant.
You might also like
clojure-write
metabase
Guide Clojure and ClojureScript development using REPL-driven workflow, coding conventions, and best practices. Use when writing, developing, or refactoring Clojure/ClojureScript code.
add-uint-support
pytorch
Add unsigned integer (uint) type support to PyTorch operators by updating AT_DISPATCH macros. Use when adding support for uint16, uint32, uint64 types to operators, kernels, or when user mentions enabling unsigned types, barebones unsigned types, or uint support.
python-design-patterns
wshobson
Python design patterns including KISS, Separation of Concerns, Single Responsibility, and composition over inheritance. Use when making architecture decisions, refactoring code structure, or evaluating when abstractions are appropriate.
python-patterns
affaan-m
Pythonic 惯用法、PEP 8 标准、类型提示以及构建健壮、高效、可维护的 Python 应用程序的最佳实践。
modular-code
parcadei
Modular Code Organization
modern-python
trailofbits
Configures Python projects with modern tooling (uv, ruff, ty). Use when creating projects, writing standalone scripts, or migrating from pip/Poetry/mypy/black.