SuperAPI AI Directory

python-refactoring

Coding & development

View repository

Updated 10-16 05:00

About this skill

Python Code Refactoring

Systematically refactor Python code, improving its internal structure without changing external behavior, and enhancing readability, maintainability, and extensibility.

Overview

  • Applicable scenarios: code refactoring, code review, code quality improvement, technical debt cleanup
  • Core principles: refactoring ≠ rewriting; keep interfaces compatible; refactor only with tests; minimal changes
  • Reference documents: distilled from 20+ real refactoring PRs in the vllm-ascend repository
  • Constraint configuration: all numeric thresholds (function line count, parameter count, etc.) are centralized in refactoring-config.json, and users can customize or disable them

Quick Reference

Tasks Reference documents
Custom constraint thresholds refactoring-config.json
Identify code issues references/code-smells.md
Choose design patterns references/design-patterns.md
Improve readability references/readability.md
Practical patterns and cases references/refactoring-in-practice.md
Generate refactoring document references/refactoring-report.md

Code smell → refactoring pattern quick reference table

After identifying a problem, use this table to quickly locate a solution:

Code smell Recommended pattern Detailed reference
Long function Extract Method、Guard Clause code-smells.md §1.1
Long parameter list dataclass parameter object, Builder design-patterns.md §1.3
Duplicated code (cross-cutting concerns) Decorator pattern design-patterns.md §2.1
Duplicated code (same process skeleton) Template method / Strategy pattern practice §Pattern 3
God class Split by responsibility, composition over inheritance practice §Patterns 2, 5
Excessive inheritance Composition + Protocol design-patterns.md §3.1
if-elif to create instances Factory pattern (registry) practice §Pattern 1
if-elif type dispatch Polymorphism / singledispatch design-patterns.md §3.4
Multiple xxx_with_yyy function variants Strategy pattern (Protocol) practice §Pattern 3
Passing composite data via dict/tuple dataclass type formalization practice §Pattern 7
Magic numbers/strings Enum (Enum / IntEnum) code-smells.md §3.3
Custom implementation duplicated with upstream Align with upstream / inherit from base class practice §Pattern 4
Oversized module (>500 lines) Separate concerns, package-ize practice §Pattern 2
Inferior path proven by benchmarks Delete dead path practice §Pattern 6

Refactoring execution workflow

┌─────────────────────────────────────────────────────────┐
│  0. 前置检查                                              │
│     - 确认有测试覆盖(无则先补关键路径测试)                  │
│     - 确认代码可正常运行                                    │
│     - 评估重构规模 → refactoring-in-practice.md 规模矩阵   │
├─────────────────────────────────────────────────────────┤
│  1. 识别问题  →  references/code-smells.md               │
│     - 通读代码,按分类逐项检查                               │
│     - 输出问题清单,按严重程度排序                            │
├─────────────────────────────────────────────────────────┤
│  2. 选择策略  →  references/refactoring-in-practice.md   │
│     - 匹配七大实战模式,选择最合适的重构路径                  │
│     - 大型重构制定分阶段计划(参考 Quantization/MoE 案例)    │
├─────────────────────────────────────────────────────────┤
│  3. 结构重构  →  references/design-patterns.md           │
│     - 对结构性问题选择合适的模式                             │
│     - 实施重构,确保接口兼容                                 │
├─────────────────────────────────────────────────────────┤
│  4. 打磨优化  →  references/readability.md               │
│     - 改善命名、结构、类型标注                               │
│     - 补充必要注释和文档                                    │
├─────────────────────────────────────────────────────────┤
│  5. 验证                                                 │
│     - 运行全部已有测试,确认无回归                            │
│     - 运行 linter / type checker                          │
│     - 对比重构前后,确认行为一致                             │
├─────────────────────────────────────────────────────────┤
│  6. 输出重构文档(可选,用户请求时生成)                       │
│     - 汇总本次重构的完整记录                                 │
│     - 生成结构化文档,可用于 PR 描述 / 团队分享 / 项目归档     │
│     - 参见 references/refactoring-report.md                  │
└─────────────────────────────────────────────────────────┘

Refactoring decision guide

When to refactor

  • Before adding new features, first refactor the related code to make it easy to extend
  • When fixing a bug, also improve the surrounding code structure along the way
  • Issues found during Code Review
  • When the code is difficult to understand or modify

When not to refactor

  • Code that is about to be deprecated
  • Core code that has no test coverage and cannot quickly have tests added
  • Urgent fixes under time pressure (fix first, refactor later)
  • Code that is not perfect but is clear enough and runs stably

Refactoring granularity control

Scale Scope Recommendation Reference case
Small Single function/method Modify directly, single commit MoE #5189 reuse upstream all_reduce (-38 lines)
Medium Single class or module Split into 2-3 commits MoE #5481 dict/tuple → dataclass (6 files)
Large Cross-module/package Make a plan, execute in phases Quantization 4-phase refactoring (36 files)

Refactoring document template

When the user requests generation of a refactoring document (such as "output refactoring document", "generate refactoring report", "write refactoring summary"), after the refactoring is complete and verified, follow the template in references/refactoring-report.md to generate the document.

The document supports tailoring by purpose (PR description / team sharing / project archive); small refactorings can use a streamlined format. See the reference document for details.


Output format

For each refactoring suggestion, output in the following format:

### [问题类型] 问题简述

**位置:** `file_path:line_number`
**问题:** 描述当前代码的问题
**方案:** 描述修复方案
**实战参考:** 匹配的实战模式(如适用)
**修复前:**
(代码片段)
**修复后:**
(代码片段)
**依据:** 引用的参考文档和具体规则

References

Detailed reference documents:

  • code-smells.md — Code smell identification and fixes (four levels: function/class/logic/module, including isinstance chain dispatch)
  • design-patterns.md — Pythonic design pattern applications (creational/structural/behavioral + singledispatch + anti-pattern warnings)
  • readability.md — Readability and maintainability improvements (naming/structure/type annotations/comments/module organization/Pythonic idioms)
  • refactoring-in-practice.md — Practical refactoring experience based on real vllm-ascend PRs (seven major patterns + safety guidelines + scale assessment matrix)
  • refactoring-report.md — Refactoring document generation (template + section filling guide + scenario adaptation + streamlined format for small refactorings)