python-refactor
複雑で読みにくいPythonコードを、可読性・保守性の高い、理解しやすいコードへと体系的に改善し、コードレビューや教育の場面でも活用できる、構造的なリファクタリングを検証しながら実行するSkill。
📜 元の英語説明(参考)
Systematic code refactoring skill that transforms complex, hard-to-understand code into clear, well-documented, maintainable code while preserving correctness. Use when users request "readable", "maintainable", or "clean" code, during code reviews flagging comprehension issues, for legacy code modernization, or in educational/onboarding contexts. Applies structured refactoring patterns with validation.
🇯🇵 日本人クリエイター向け解説
複雑で読みにくいPythonコードを、可読性・保守性の高い、理解しやすいコードへと体系的に改善し、コードレビューや教育の場面でも活用できる、構造的なリファクタリングを検証しながら実行するSkill。
※ jpskill.com 編集部が日本のビジネス現場向けに補足した解説です。Skill本体の挙動とは独立した参考情報です。
下記のコマンドをコピーしてターミナル(Mac/Linux)または PowerShell(Windows)に貼り付けてください。 ダウンロード → 解凍 → 配置まで全自動。
mkdir -p ~/.claude/skills && cd ~/.claude/skills && curl -L -o python-refactor.zip https://jpskill.com/download/9108.zip && unzip -o python-refactor.zip && rm python-refactor.zip
$d = "$env:USERPROFILE\.claude\skills"; ni -Force -ItemType Directory $d | Out-Null; iwr https://jpskill.com/download/9108.zip -OutFile "$d\python-refactor.zip"; Expand-Archive "$d\python-refactor.zip" -DestinationPath $d -Force; ri "$d\python-refactor.zip"
完了後、Claude Code を再起動 → 普通に「動画プロンプト作って」のように話しかけるだけで自動発動します。
💾 手動でダウンロードしたい(コマンドが難しい人向け)
- 1. 下の青いボタンを押して
python-refactor.zipをダウンロード - 2. ZIPファイルをダブルクリックで解凍 →
python-refactorフォルダができる - 3. そのフォルダを
C:\Users\あなたの名前\.claude\skills\(Win)または~/.claude/skills/(Mac)へ移動 - 4. Claude Code を再起動
⚠️ ダウンロード・利用は自己責任でお願いします。当サイトは内容・動作・安全性について責任を負いません。
🎯 このSkillでできること
下記の説明文を読むと、このSkillがあなたに何をしてくれるかが分かります。Claudeにこの分野の依頼をすると、自動で発動します。
📦 インストール方法 (3ステップ)
- 1. 上の「ダウンロード」ボタンを押して .skill ファイルを取得
- 2. ファイル名の拡張子を .skill から .zip に変えて展開(macは自動展開可)
- 3. 展開してできたフォルダを、ホームフォルダの
.claude/skills/に置く- · macOS / Linux:
~/.claude/skills/ - · Windows:
%USERPROFILE%\.claude\skills\
- · macOS / Linux:
Claude Code を再起動すれば完了。「このSkillを使って…」と話しかけなくても、関連する依頼で自動的に呼び出されます。
詳しい使い方ガイドを見る →- 最終更新
- 2026-05-18
- 取得日時
- 2026-05-18
- 同梱ファイル
- 1
📖 Skill本文(日本語訳)
※ 原文(英語/中国語)を Gemini で日本語化したものです。Claude 自身は原文を読みます。誤訳がある場合は原文をご確認ください。
Python リファクタリング
目的
複雑で理解しにくい Python コードを、明確で、十分にドキュメント化され、保守可能なコードに変換し、正確性を維持します。このスキルは、正確性や妥当なパフォーマンスを犠牲にすることなく、人間の理解を優先する体系的なリファクタリングをガイドします。
呼び出すべき時
このスキルは、以下の場合に呼び出します。
- ユーザーが明示的に「人間的」、「読みやすい」、「保守可能」、「クリーン」、または「リファクタリング」によるコード改善を要求した場合
- コードレビュープロセスで理解度または保守性の問題が指摘された場合
- 現代化が必要なレガシーコードを扱っている場合
- チームのオンボーディングまたは教育の文脈のためにコードを準備している場合
- コードの複雑性メトリクスが妥当な閾値を超えている場合
- 関数またはモジュールが理解または変更しにくい場合
- 危険信号の指標: 散在した関数とグローバルな状態を持つ 500 行を超えるファイル、複数の
globalステートメント、明確なモジュール/クラスの構成がない、ビジネスロジックと混在した構成
このスキルは、以下の場合には呼び出さないでください。
- コードがパフォーマンスクリティカルであり、プロファイリングで最初に最適化が必要であることが示されている場合
- コードが削除または置換される予定の場合
- 外部依存関係がアップストリームへの貢献を必要とする場合
- ユーザーが明示的に読みやすさよりもパフォーマンスの最適化を要求した場合
コア原則
以下の原則を優先順位に従って守ってください。
- 複雑なコードには構造化された OOP を優先する - 共有状態、複数の関心事、または散在したグローバル関数を持つコードは、適切に構成されたクラスとモジュールに再構築する必要があります。グローバルな状態と絡み合った依存関係を持つスクリプトのようなコードは、OOP から最も恩恵を受けます。ただし、純粋な関数を持つ単純なモジュール、click/argparse を使用する CLI ツール、および関数型データパイプラインは、クラスに強制的に入れる必要はありません。
- 巧妙さよりも明確さ - 明示的で明白なコードは、暗黙的で巧妙なコードに勝ります
- 正確性を維持する - すべてのテストに合格する必要があります。動作は同一のままでなければなりません
- 単一責任 - 各クラスと関数は、1 つのことをうまく行う必要があります (SOLID 原則)
- 自己文書化された構造 - コード構造は何を説明し、コメントは理由を説明します
- 段階的な開示 - 複雑さを一度にすべてではなく、レイヤーで明らかにします
- 妥当なパフォーマンス - 明示的な承認なしに、2 倍以上のパフォーマンスを犠牲にしないでください
主要な制約
常に以下の制約を守ってください。
- 設計による安全性 - 破壊的な変更には必須の移行チェックリストを使用します。新しい構造を作成し、すべての使用箇所を検索し、すべてを移行し、検証し、その後でのみ古いコードを削除します。100% の移行が検証されるまで、コードを絶対に削除しないでください。
- 最初に静的解析 - テストの前に
flake8 --select=F821,E0602を実行して、NameError をすぐに検出します - 動作を維持する - リファクタリング後、既存のすべてのテストに合格する必要があります
- パフォーマンスの低下なし - 明示的なユーザーの承認なしに、2 倍以上のパフォーマンスを低下させないでください
- API の変更なし - 明示的に要求され、文書化されない限り、パブリック API は変更されません
- 過剰な設計なし - 単純なコードは単純なままにします。不要な抽象化を追加しないでください
- 魔法なし - フレームワークの魔法、メタプログラミングは、絶対に必要でない限り使用しません
- 継続的に検証する - 論理的な変更を行うたびに、静的解析 + テストを実行します
リグレッション防止 (必須)
リファクタリングによって、技術的、論理的、または機能的なリグレッションが発生してはなりません。
リファクタリングセッションの前に、references/REGRESSION_PREVENTION.md を読んで適用してください。
各リファクタリングセッションの前に:
- テストスイートが 100% で合格する
- 対象コードのカバレッジ >= 80% (そうでない場合は、最初にテストを作成する)
- 重要なエッジケースのゴールデンアウトプットをキャプチャする
- 静的解析のベースラインを保存する
各マイクロチェンジの後 (最後にではなく、すべての単一のチェンジの後):
flake8 --select=F821,E999-> エラー 0pytest -x-> すべて合格- 変更されていない動作について、1 つのエッジケースをスポットチェックする
いずれかのチェックが失敗した場合: STOP -> REVERT -> ANALYZE -> FIX APPROACH -> RETRY
リグレッション = リファクタリングの完全な失敗
リファクタリングワークフロー
各ステップで検証を行いながら、4 つのフェーズでリファクタリングを実行します。
フェーズ 1: 分析
変更を加える前に、コードを包括的に分析します。
- リファクタリングされるコードベースセクション全体を読んで、コンテキストを理解します
- アンチパターンリファレンス (
references/anti-patterns.mdを参照) を使用して、読みやすさの問題を特定します。- スクリプトのような/手続き的なコード (グローバルな状態、散在した関数、明確な構造がない) を確認します
- God Object/Class (クラスが多すぎる) を確認します
- 複雑なネストされた条件、長い関数、マジックナンバー、不可解な名前など
- アーキテクチャを評価します (
references/oop_principles.mdを参照)。- コードは適切なクラスとモジュールで構成されていますか?
- カプセル化する必要があるグローバルな状態はありますか?
- 責任は適切に分離されていますか?
- SOLID 原則は守られていますか?
- ハードコードされた依存関係の代わりに、依存性注入が使用されていますか?
scripts/measure_complexity.pyまたはscripts/analyze_multi_metrics.pyを使用して、現在のメトリクスを測定します- リンティング分析を実行します (使用するツールについては、以下のツール推奨事項を参照してください)
- テストカバレッジを確認します - リファクタリング前に埋める必要のあるギャップを特定します
- 分析テンプレート (
assets/templates/analysis_template.mdを参照) を使用して、調査結果を文書化します
出力: 影響とリスクによって優先順位付けされた問題のリスト。
フェーズ 2: 計画
設計による安全性 を備えた体系的なリファクタリングアプローチを計画します。
-
変更をタイプ別に識別します。
- 非破壊的: 名前変更、ドキュメント、型ヒント -> 低リスク
- 破壊的: グローバルの削除、関数の削除、API の置換 -> 高リスク
-
破壊的な変更の場合 - 移行計画を作成する (必須):
- 削除する各要素のすべての使用箇所を検索します
- 見つかったすべての使用箇所をファイル、行番号、および使用タイプで文書化します
- 完全な移行計画を作成できない場合は、破壊的な変更を進めることはできません
-
提案された各変更のリスク評価 (低/中/高)
-
依存関係の特定 - このコードに他に何が依存していますか?
-
テスト戦略 - どのようなテストが必要ですか?何がブ
📜 原文 SKILL.md(Claudeが読む英語/中国語)を展開
Python Refactor
Purpose
Transform complex, hard-to-understand Python code into clear, well-documented, maintainable code while preserving correctness. This skill guides systematic refactoring that prioritizes human comprehension without sacrificing correctness or reasonable performance.
When to Invoke
Invoke this skill when:
- User explicitly requests "human", "readable", "maintainable", "clean", or "refactor" code improvements
- Code review processes flag comprehension or maintainability issues
- Working with legacy code that needs modernization
- Preparing code for team onboarding or educational contexts
- Code complexity metrics exceed reasonable thresholds
- Functions or modules are difficult to understand or modify
- RED FLAG indicators: file >500 lines with scattered functions and global state, multiple
globalstatements, no clear module/class organization, configuration mixed with business logic
Do NOT invoke this skill when:
- Code is performance-critical and profiling shows optimization is needed first
- Code is scheduled for deletion or replacement
- External dependencies require upstream contributions instead
- User explicitly requests performance optimization over readability
Core Principles
Follow these principles in priority order:
- Prefer structured OOP for complex code - Code with shared state, multiple concerns, or scattered global functions should be restructured into well-organized classes and modules. Script-like code with global state and tangled dependencies benefits most from OOP. However, simple modules with pure functions, CLI tools using click/argparse, and functional data pipelines don't need to be forced into classes.
- Clarity over cleverness - Explicit, obvious code beats implicit, clever code
- Preserve correctness - All tests must pass; behavior must remain identical
- Single Responsibility - Each class and function should do one thing well (SOLID principles)
- Self-documenting structure - Code structure tells what, comments explain why
- Progressive disclosure - Reveal complexity in layers, not all at once
- Reasonable performance - Never sacrifice >2x performance without explicit approval
Key Constraints
ALWAYS observe these constraints:
- SAFETY BY DESIGN - Use mandatory migration checklists for destructive changes. Create new structure, search all usages, migrate all, verify, only then remove old code. NEVER remove code before 100% migration verified.
- STATIC ANALYSIS FIRST - Run
flake8 --select=F821,E0602before tests to catch NameErrors immediately - PRESERVE BEHAVIOR - All existing tests must pass after refactoring
- NO PERFORMANCE REGRESSION - Never degrade performance >2x without explicit user approval
- NO API CHANGES - Public APIs remain unchanged unless explicitly requested and documented
- NO OVER-ENGINEERING - Simple code stays simple; don't add unnecessary abstraction
- NO MAGIC - No framework magic, no metaprogramming unless absolutely necessary
- VALIDATE CONTINUOUSLY - Run static analysis + tests after each logical change
Regression Prevention (MANDATORY)
Refactoring must NEVER introduce technical, logical, or functional regressions.
Read and apply references/REGRESSION_PREVENTION.md before any refactoring session.
Before each refactoring session:
- Test suite passes at 100%
- Coverage >= 80% on target code (if not, write tests FIRST)
- Golden outputs captured for critical edge cases
- Static analysis baseline saved
After each micro-change (not at the end, EVERY SINGLE ONE):
flake8 --select=F821,E999-> 0 errorspytest -x-> all passing- Spot check 1 edge case for unchanged behavior
If ANY check fails: STOP -> REVERT -> ANALYZE -> FIX APPROACH -> RETRY
ANY REGRESSION = TOTAL FAILURE OF THE REFACTORING
Refactoring Workflow
Execute refactoring in four phases with validation at each step.
Phase 1: Analysis
Before making any changes, analyze the code comprehensively:
- Read the entire codebase section being refactored to understand context
- Identify readability issues using the anti-patterns reference (see
references/anti-patterns.md):- Check for script-like/procedural code (global state, scattered functions, no clear structure)
- Check for God Objects/Classes (classes doing too much)
- Complex nested conditionals, long functions, magic numbers, cryptic names, etc.
- Assess architecture (see
references/oop_principles.md):- Is code organized in proper classes and modules?
- Is there global state that should be encapsulated?
- Are responsibilities properly separated?
- Are SOLID principles followed?
- Is dependency injection used instead of hard-coded dependencies?
- Measure current metrics using
scripts/measure_complexity.pyorscripts/analyze_multi_metrics.py - Run linting analysis (see Tooling Recommendations below for which tool to use)
- Check test coverage - Identify gaps that need filling before refactoring
- Document findings using the analysis template (see
assets/templates/analysis_template.md)
Output: Prioritized list of issues by impact and risk.
Phase 2: Planning
Plan the refactoring approach systematically with safety-by-design:
-
Identify changes by type:
- Non-destructive: Renames, documentation, type hints -> Low risk
- Destructive: Removing globals, deleting functions, replacing APIs -> High risk
-
For DESTRUCTIVE changes - CREATE MIGRATION PLAN (MANDATORY):
- Search for ALL usages of each element to be removed
- Document every found usage with file, line number, and usage type
- If you cannot create a complete migration plan, you CANNOT proceed with the destructive change
-
Risk assessment for each proposed change (Low/Medium/High)
-
Dependency identification - What else depends on this code?
-
Test strategy - What tests are needed? What might break?
-
Change ordering - Sequence changes from safest to riskiest
-
Expected outcomes - Document what metrics should improve and by how much
Output: Refactoring plan with sequenced changes, migration plans for destructive changes, test strategy, and rollback plan.
Phase 3: Execution
Apply refactoring patterns using safety-by-design workflow.
For NON-DESTRUCTIVE changes (safe to do anytime):
- Rename variables/functions for clarity
- Extract magic numbers/strings to named constants
- Add/improve documentation and type hints
- Add guard clauses to reduce nesting
For DESTRUCTIVE changes (removing/replacing code) - STRICT PROTOCOL:
- CREATE new structure (no removal yet) - write new classes/functions, add tests
- SEARCH comprehensively for ALL usages of the element being removed
- CREATE migration checklist documenting every found usage
- MIGRATE one usage at a time, checking off the list, running static analysis + tests after each
- VERIFY complete migration - re-run original searches, should find zero old references
- REMOVE old code only after 100% migration verified
Execution Rules
- NEVER skip the migration checklist for destructive changes
- Run static analysis BEFORE tests - Catch NameErrors immediately
- One pattern at a time - Never mix multiple refactoring patterns in one change
- Atomic commits - Each migration step gets its own commit
- Stop on ANY error - Static analysis errors OR test failures require immediate fix/revert
Refactoring order (recommended sequence):
- Transform script-like code to proper architecture (if code has global state and scattered functions). See
references/examples/script_to_oop_transformation.md - Rename variables/functions for clarity
- Extract magic numbers/strings to named constants (as class constants or enums)
- Add/improve documentation and type hints
- Extract methods to reduce function length
- Simplify conditionals with guard clauses
- Reduce nesting depth
- Final review: Ensure separation of concerns is clean
Output: Refactored code passing all tests with clear commit history.
Phase 4: Validation
Validate improvements objectively:
-
Run static analysis FIRST (catch errors before tests):
flake8 <file> --select=F821,E0602 # Undefined names/variables flake8 <file> --select=F401 # Unused imports flake8 <file> # Full quality checkMANDATORY: Zero F821 and E0602 errors required
-
Run full test suite - 100% pass rate required
-
Validate architecture improvements:
- Confirm global state has been eliminated or properly encapsulated
- Verify code is organized in proper modules/classes
- Check that responsibilities are properly separated
- Validate against SOLID principles (see
references/oop_principles.md)
-
Compare before/after metrics using
scripts/measure_complexity.pyorscripts/analyze_multi_metrics.py -
Performance regression check - Run
scripts/benchmark_changes.pyfor hot paths -
Generate summary report using format from
assets/templates/summary_template.md -
Flag for human review if:
- Performance degraded >10%
- Public API signatures changed
- Test coverage decreased
- Significant architectural changes were made
Output: Comprehensive validation report with test results, metrics comparison, performance benchmarks, and quality summary.
Refactoring Patterns
Apply these patterns systematically. See references/patterns.md for full catalog with examples.
Key Patterns (summary)
- Guard Clauses - Replace nested conditionals with early returns. See
references/patterns.md - Extract Method - Split large functions into focused units. Resets nesting counter (most powerful for cognitive complexity)
- Dictionary Dispatch - Eliminate if-elif chains with lookup tables
- Match Statement (Python 3.10+) - switch counts as +1 total, not per branch
- Named Boolean Conditions - Extract complex boolean expressions into named variables
- Encapsulate Global State - Move globals into classes with proper encapsulation
- Group Related Functions - Organize scattered functions into classes by responsibility
- Create Domain Models - Replace primitive dicts with dataclasses and enums
- Apply Dependency Injection - Replace hard-coded dependencies with injected ones
See references/cognitive_complexity_guide.md for cognitive complexity calculation rules and reduction patterns.
Naming Conventions
- Variables: Descriptive names, booleans as
is_active/has_permission/can_edit, collections as plurals - Functions: Verb + object (
calculate_total,validate_email), boolean queries asis_valid()/has_items() - Constants:
UPPERCASE_WITH_UNDERSCORES, replace magic numbers/strings - Classes: PascalCase nouns (
UserAccount,PaymentProcessor)
Documentation Patterns
- Function Docstrings - Document purpose, args, returns, raises (Google style preferred)
- Module Documentation - Purpose and key dependencies
- Inline Comments - Only for non-obvious "why"
- Type Hints - All public APIs and complex internals
OOP Transformation Patterns
For transforming script-like code to structured OOP. See references/examples/script_to_oop_transformation.md for a complete guide and references/oop_principles.md for SOLID principles.
Anti-Patterns to Fix
See references/anti-patterns.md for the full catalog. Priority order:
Critical: Script-like/procedural code with global state, God Object/God Class High: Complex nested conditionals (>3 levels), long functions (>30 lines), magic numbers, cryptic names, missing type hints, missing docstrings Medium: Duplicate code, primitive obsession, long parameter lists (>5) Low: Inconsistent naming, redundant comments, unused imports
Tooling Recommendations
Primary Stack: Ruff + Complexipy (recommended for new projects)
pip install ruff complexipy radon wily
ruff check src/ # Fast linting (Rust, replaces flake8+plugins)
complexipy src/ --max-complexity-allowed 15 # Cognitive complexity (Rust)
radon mi src/ -s # Maintainability Index
See references/cognitive_complexity_guide.md for complete configuration (pyproject.toml, pre-commit hooks, GitHub Actions, CLI usage).
Alternative: Flake8 (for projects already using it)
The scripts/analyze_with_flake8.py and scripts/compare_flake8_reports.py scripts use flake8. See references/flake8_plugins_guide.md for the curated plugin list.
Multi-Metric Analysis
Use scripts/analyze_multi_metrics.py to combine cognitive complexity (complexipy), cyclomatic complexity (radon), and maintainability index in a single report.
| Metric | Tool | Use |
|---|---|---|
| Cognitive Complexity | complexipy | Human comprehension |
| Cyclomatic Complexity | ruff (C901), radon | Test planning |
| Maintainability Index | radon | Overall code health |
Metric Targets
- Cyclomatic complexity: <10 per function (warning at 15, error at 20)
- Cognitive complexity: <15 per function (SonarQube default, warning at 20)
- Function length: <30 lines (warning at 50)
- Nesting depth: <=3 levels
- Docstring coverage: >80% for public functions
- Type hint coverage: >90% for public APIs
Historical Tracking with Wily
Monitor trends over time, not just thresholds. See references/cognitive_complexity_guide.md for setup and CI integration.
Common Refactoring Mistakes
See references/REGRESSION_PREVENTION.md for the full guide. Key traps:
- Incomplete Migration - Removing old code before ALL usages are migrated (causes NameErrors)
- Partial Pattern Application - Applying refactoring to some functions but not others
- Breaking Public APIs - Changing function signatures used by external code
- Assuming Tests Cover Everything - Tests pass but runtime errors occur (run static analysis!)
Output Format
Structure refactoring output using the template from assets/templates/summary_template.md. Include:
- Changes made with rationale and risk level
- Before/after metrics comparison table
- Test results and performance impact
- Risk assessment and human review recommendation
Integration with Same-Package Skills
- python-testing-patterns - Set up tests before refactoring, validate coverage after
- python-performance-optimization - Deep profiling before/after refactoring
- python-packaging - If refactoring a library, handle pyproject.toml and distribution
- uv-package-manager - Use
uv run ruff,uv run complexipyfor tool execution - async-python-patterns - Reference async patterns when refactoring async code
Edge Cases and Limitations
When NOT to Refactor: Performance-critical optimized code (profile first), code scheduled for deletion, external dependencies (contribute upstream), stable legacy code nobody needs to modify.
Limitations: Cannot improve algorithmic complexity (that's algorithm change, not refactoring). Cannot add domain knowledge not in code/comments. Cannot guarantee correctness without tests. Code style preferences vary - adjust based on team conventions.
Examples
See references/examples/ for before/after examples:
script_to_oop_transformation.md- Complete transformation from script-like code to clean OOP architecturepython_complexity_reduction.md- Nested conditionals and long functionstypescript_naming_improvements.md- Variable and function naming patterns (cross-language reference)
Success Criteria
Refactoring is successful when:
- ZERO regressions - All existing tests pass, behavior unchanged
- Golden master match - Identical output for documented critical cases
- Complexity metrics improved (documented in summary)
- No performance regression >10% (or explicit approval obtained)
- Documentation coverage improved
- Code is easier for humans to understand
- No new security vulnerabilities introduced
- Changes are atomic and well-documented in git history
- Wily trend - Complexity not increased compared to previous commit
- Static analysis shows improvement