SuperAPI AI Directory

python-simplifier

Coding & development

View repository

Updated 10-16 09:44

About this skill

Python Code Simplification and Refactoring Guide

Overview

Use this skill when the readability, structure, or duplication of Python code already affects understanding and maintenance, but existing behavior must not be changed.

The goal is not to "write it shorter," but tofully preserve the original functionality, outputs, side effects, exception behavior, and public interfaceswhile reducing complexity, improving readability, and making subsequent changes safer.

Applicable Scenarios

Use when one or more of the following situations occur:

  • There is duplicated validation, conversion, or branching logic
  • Conditions are deeply nested, and the main flow is unclear
  • if/elif The branch chain is very long, and most of it is value dispatch
  • There are intermediate variables that do not express additional semantics
  • There are too many data classes or boilerplate code, obscuring the core intent
  • Manual loops are more verbose than comprehensions or built-in functions
  • Magic numbers and magic strings reduce code comprehensibility

Inapplicable Scenarios

Do not use this skill as the primary guidance in the following situations:

  • Cross-module refactoring, architectural redesign
  • Changes whose primary goal is performance optimization
  • Modifications that change the API, data structures, exception protocol, or business behavior
  • The current task involves only local code, but it sprawls into large-scale cleanup
  • Introducing more obscure and harder-to-debug styles in order to reduce the number of lines

Scope Constraints

  • By default, only handle the code involved in the current task, the current diff, or files explicitly specified by the user.
  • Prioritize local, provably safe simplifications, and do not perform repository-level "incidental cleanup."
  • Do not cram multiple responsibilities into the same function just because the logic is adjacent.
  • If semantics cannot be proven to remain unchanged, stop simplifying and keep the original implementation.

Behavior Preservation Checklist

Unless the user explicitly requests otherwise, the following must remain unchanged during refactoring:

  • Return values and return types
  • Side effects and object mutation behavior
  • Evaluation order
  • Lazy/immediate evaluation semantics
  • Externally visible or test-covered exception types and exception messages
  • Logging, metrics, tracing, retries, and other behavior
  • Public function signatures and data model structures

Division of Labor with Other Python Skills

  • python-code-quality: Responsible for formatting, linting, type checking, and basic conventions
  • python-best-practices: Responsible for broader Python design, performance, data structures, and concurrency recommendations
  • python-code-review: Responsible for overall quality review and pre-commit checks
  • python-simplifier: Focuses on, withoutchanging behavior, reducing complexity, eliminating duplication, and improving readability

Simplification Workflow

  1. First determine the smallest safely modifiable scope.
  2. Determine whether the current main problem is duplication, nesting, branch bloat, boilerplate code, or state noise.
  3. Choose the clearest local approach, not the shortest way to write it.
  4. Keep behavior completely consistent, including boundary conditions and failure paths.
  5. Validate the result with tests,ruff and basedpyright .
  6. Only describe those changes that truly raise the cost of understanding.

Core Principles

  1. Keep functionality unchanged: Refactoring only changes code structure, not code behavior
  2. Readability first: Code is first for people to read, and only second for machines to execute
  3. Single responsibility: Each function and class does only one thing
  4. Eliminate duplication: Follow the DRY (Don't Repeat Yourself) principle
  5. Simplify appropriately: Avoid over-compression that reduces readability

Eliminate duplicated code

Extract common logic into functions

Only extract when the duplicated logic is semantically truly the same, not merely "looks similar".

# ❌ 重复代码
def process_admin(user):
    if not user.get("name"):
        raise ValueError("名称不能为空")
    if len(user["name"]) > 50:
        raise ValueError("名称过长")
    # admin 逻辑...

def process_member(user):
    if not user.get("name"):
        raise ValueError("名称不能为空")
    if len(user["name"]) > 50:
        raise ValueError("名称过长")
    # member 逻辑...

# ✅ 提取公共验证
def validate_user_name(user: dict) -> None:
    if not user.get("name"):
        raise ValueError("名称不能为空")
    if len(user["name"]) > 50:
        raise ValueError("名称过长")

def process_admin(user: dict) -> None:
    validate_user_name(user)
    # admin 逻辑...

def process_member(user: dict) -> None:
    validate_user_name(user)
    # member 逻辑...

Use parameterization instead of similar functions

If multiple functions differ only in input constants while the flow is exactly the same, parameterization can be considered.

# ❌ 相似的多个函数
def send_welcome_email(user_email: str) -> None:
    subject = "欢迎加入!"
    body = "感谢您的注册..."
    _send_email(user_email, subject, body)

def send_reset_email(user_email: str) -> None:
    subject = "密码重置"
    body = "点击链接重置密码..."
    _send_email(user_email, subject, body)

# ✅ 统一函数 + 枚举
from enum import Enum

class EmailTemplate(Enum):
    WELCOME = ("欢迎加入!", "感谢您的注册...")
    RESET = ("密码重置", "点击链接重置密码...")

def send_email(user_email: str, template: EmailTemplate) -> None:
    subject, body = template.value
    _send_email(user_email, subject, body)

Simplify conditional logic

Use early returns instead of deep nesting

When every failure condition can naturally exit early, prefer Guard Clause to flatten the main flow.

# ❌ 深层嵌套(箭头形代码)
def process_order(order):
    if order is not None:
        if order.is_valid():
            if order.user.is_active():
                if order.items:
                    return fulfill_order(order)
    return None

# ✅ 提前返回(Guard Clause)
def process_order(order: Order | None) -> OrderResult | None:
    if order is None:
        return None
    if not order.is_valid():
        return None
    if not order.user.is_active():
        return None
    if not order.items:
        return None
    return fulfill_order(order)

Use dictionaries instead of long if-elif chains

Suitable for simple "input value -> output value" mappings; if the branches also contain validation, side effects, or multi-step logic, do not force the replacement.

# ❌ 冗长的 if-elif 链
def get_status_label(status: str) -> str:
    if status == "pending":
        return "待处理"
    elif status == "processing":
        return "处理中"
    elif status == "completed":
        return "已完成"
    elif status == "cancelled":
        return "已取消"
    else:
        return "未知"

# ✅ 字典映射
STATUS_LABELS: dict[str, str] = {
    "pending": "待处理",
    "processing": "处理中",
    "completed": "已完成",
    "cancelled": "已取消",
}

def get_status_label(status: str) -> str:
    return STATUS_LABELS.get(status, "未知")

Use match-case for complex branches (Python 3.10+)

When what you are expressing is structured pattern matching, not just simple value mapping,match-case is clearer.

# ✅ 使用 match-case
def handle_event(event: dict) -> str:
    match event["type"]:
        case "click":
            return handle_click(event)
        case "hover":
            return handle_hover(event)
        case "submit":
            return handle_submit(event)
        case _:
            return handle_unknown(event)

Simplify collection operations

Use comprehensions instead of loops

Comprehensions are suitable for expressing simple, linear transformations. Overly long or multi-level nested comprehensions instead reduce readability.

# ❌ 命令式循环
result = []
for item in items:
    if item.is_active():
        result.append(item.name.upper())

# ✅ 列表推导式
result = [item.name.upper() for item in items if item.is_active()]

# 字典推导式
user_map = {user.id: user.name for user in users}

# 集合推导式
unique_tags = {tag for item in items for tag in item.tags}

Use built-in functions

When sum、any、all、max and other built-in functions can express intent more directly, prefer using them.

# ❌ 手动循环
total = 0
for price in prices:
    total += price

has_admin = False
for user in users:
    if user.role == "admin":
        has_admin = True
        break

# ✅ 内置函数
total = sum(prices)
has_admin = any(user.role == "admin" for user in users)
all_active = all(user.is_active() for user in users)
max_price = max(prices, default=0)

Simplify function design

Remove unnecessary intermediate variables

Only consider deleting intermediate variables when they carry no domain semantics and do not help with debugging.

# ❌ 多余的中间赋值
def is_valid_age(age: int) -> bool:
    result = age >= 0 and age <= 150
    return result

# ✅ 直接返回
def is_valid_age(age: int) -> bool:
    return 0 <= age <= 150

Use dataclass instead of cumbersome class definitions

Suitable for classes primarily carrying data; if the class contains complex invariants, construction rules, or behavioral logic, do not mechanically replace it.

# ❌ 样板代码过多
class Point:
    def __init__(self, x: float, y: float):
        self.x = x
        self.y = y

    def __repr__(self):
        return f"Point(x={self.x}, y={self.y})"

    def __eq__(self, other):
        return self.x == other.x and self.y == other.y

# ✅ 使用 dataclass
from dataclasses import dataclass

@dataclass
class Point:
    x: float
    y: float

Use | to merge dictionaries (Python 3.9+)

Provided the target Python version allows it, prefer the clearer modern syntax.

# ❌ 旧方式
merged = {**defaults, **overrides}

# ✅ 更清晰的方式
merged = defaults | overrides

Eliminate magic values

Replace numbers and strings with unclear meaning with named constants, enums, or semantic configuration.

# ❌ 含义不明的数字和字符串
if status == 2:
    send_alert()

if response.status_code == 429:
    time.sleep(60)

# ✅ 使用命名常量或枚举
from enum import IntEnum

class OrderStatus(IntEnum):
    PENDING = 1
    CONFIRMED = 2
    SHIPPED = 3

RATE_LIMIT_STATUS = 429
RATE_LIMIT_WAIT_SECONDS = 60

if status == OrderStatus.CONFIRMED:
    send_alert()

if response.status_code == RATE_LIMIT_STATUS:
    time.sleep(RATE_LIMIT_WAIT_SECONDS)

Refactor context management

Prefer context managers to reduce the risk of resource leaks and make the resource lifecycle more obvious.

# ❌ 手动资源管理
file = open("data.txt")
try:
    content = file.read()
finally:
    file.close()

# ✅ 使用 with 语句
with open("data.txt") as file:
    content = file.read()

# 多个上下文管理器
with open("input.txt") as src, open("output.txt", "w") as dst:
    dst.write(src.read())

Common Misconceptions

  • Do not change all loops into comprehensions. Overly long or multi-level comprehensions are often harder to read.
  • Do not change all if/elif into dictionaries. As long as the branches contain side effects, multi-step logic, or validation, the original writing may be clearer.
  • Do not extract all duplication into helpers. Over-abstraction fragments the context and instead affects understanding.
  • Do not compress the implementation into one line for the sake of "shorter code", sacrificing debuggability and maintainability.
  • Do not change all classes into dataclass. Behavioral classes and classes with invariants often need explicit structure.
  • Do not merge logic that "looks similar but is semantically different," otherwise future business evolution will become more dangerous.

Quick judgment heuristics

  • Duplicate logic appears more than 2 times: check whether it can really be extracted
  • Nesting exceeds 3 levels: prioritize Guard Clause
  • Value dispatch branches exceed 4: consider dictionary mapping or match-case
  • Function length exceeds about 30 lines: check whether multiple responsibilities are mixed in
  • More than 5 parameters: check whether a clearer data object or interface is needed

These are only reminders for you to check, not automatic rewriting rules.

Refactoring checklist

Compare against this checklist before and after refactoring:

Identify refactoring opportunities:

  • Duplicate code blocks exist (usually ≥3 lines of identical logic; in practice, judge flexibly based on code complexity)
  • Function exceeds 30 lines
  • Nesting level exceeds 3 levels
  • Function parameters exceed 5
  • Magic numbers/strings exist
  • Long if-elif chain (more than 4 branches)

Keep behavior consistent:

  • Return values, exceptions, logs, and side effects remain unchanged
  • No change to evaluation order or lazy behavior
  • No modification of public interfaces or data structures

Verify after refactoring:

  • All tests pass
  • Code readability improved
  • No new side effects introduced
  • Type annotations complete
  • ruff format、ruff check and basedpyright check has no errors

Bottom line

Good Python simplification reduces the friction of reading and maintenance, not the amount of information.

Prioritize explicit, local, provably safe refactoring, so that the next person reading the code can understand it faster and is less likely to break it.