pythonic-style

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Pythonic Code Style

Pythonic Code Style

任务目标

Task Objectives

  • 本 Skill 用于:分析和改进 Python 代码风格,使其更符合 Python 语言特性和最佳实践
  • 能力包含:
    • 代码风格分析:识别非 Pythonic 模式,提供改进建议
    • Pythonic 惯用法:列表推导、生成器、上下文管理器、装饰器、元类等
    • 设计模式应用:SOLID 原则、描述符协议、迭代器协议等
    • 性能优化:内存优化、计算优化、I/O 优化、并发模式、缓存策略
    • 重构指导:代码异味检测、重构技巧、重构模式、重构流程
    • 实战模板:提供可直接使用的代码模板(140+ 个)
  • 触发条件:
    • 用户展示代码并请求"如何更 Python 地实现"
    • 用户询问"这段代码是否 Pythonic"
    • 用户需要代码审查和风格改进建议
    • 用户询问 Python 特定语法的最佳实践
    • 用户需要性能优化或重构建议
    • 用户请求高级 Python 模式或设计模式
  • This Skill is used to: analyze and improve Python code style to make it more in line with Python language features and best practices
  • Capabilities include:
    • Code Style Analysis: Identify non-Pythonic patterns and provide improvement suggestions
    • Pythonic Idioms: List comprehensions, generators, context managers, decorators, metaclasses, etc.
    • Design Pattern Application: SOLID principles, descriptor protocol, iterator protocol, etc.
    • Performance Optimization: Memory optimization, computation optimization, I/O optimization, concurrency patterns, caching strategies
    • Refactoring Guidance: Code smell detection, refactoring techniques, refactoring patterns, refactoring processes
    • Practical Templates: Provide ready-to-use code templates (140+)
  • Trigger Conditions:
    • Users present code and ask "how to implement it more Pythonically"
    • Users ask "is this code Pythonic"
    • Users need code review and style improvement suggestions
    • Users ask about best practices for specific Python syntax
    • Users need performance optimization or refactoring suggestions
    • Users request advanced Python patterns or design patterns

核心理念

Core Concepts

Friendly Python = User-Friendly + Maintainer-Friendly

Friendly Python = User-Friendly + Maintainer-Friendly

┌──────────────────────────────────────────────────────────┐
│           FRIENDLY PYTHON = User-Friendly Python         │
├────────────────────────────────┬─────────────────────────┤
│   User-Friendly               │   Maintainer-Friendly     │
│   ─────────────────           │   ─────────────────      │
│   • Sensible defaults         │   • Single change point  │
│   • Minimal required params   │   • Registry over if-else│
│   • Hidden resource mgmt      │   • Explicit over magic  │
│   • Simple → complex path     │   • Readable & debuggable│
└────────────────────────────────┴─────────────────────────┘
┌──────────────────────────────────────────────────────────┐
│           FRIENDLY PYTHON = User-Friendly Python         │
├────────────────────────────────┬─────────────────────────┤
│   User-Friendly               │   Maintainer-Friendly     │
│   ─────────────────           │   ─────────────────      │
│   • Sensible defaults         │   • Single change point  │
│   • Minimal required params   │   • Registry over if-else│
│   • Hidden resource mgmt      │   • Explicit over magic  │
│   • Simple → complex path     │   • Readable & debuggable│
└────────────────────────────────┴─────────────────────────┘

设计原则

Design Principles

1. 用户友好 (User-Friendly)

1. User-Friendly

  • 默认提供合理值:让快速启动无需阅读文档
  • 最少必需参数:隐藏复杂的对象组装
  • 透明的资源管理:使用上下文管理器或统一入口
  • 简单到复杂:简单路径是默认,复杂需求可显式扩展
  • Provide sensible defaults: Enable quick start without reading documentation
  • Minimal required parameters: Hide complex object assembly
  • Transparent resource management: Use context managers or unified entry points
  • Simple to complex: Simple path is the default, complex requirements can be explicitly extended

2. 维护友好 (Maintainer-Friendly)

2. Maintainer-Friendly

  • 单点修改:添加新策略/命令/实现时,收敛到一个修改点
  • 注册表替代 if-else:使用注册表/插件表替代条件分支链
  • 谨慎使用魔法:自动扫描和动态导入需要评估可读性和可调试性
  • Single change point: When adding new strategies/commands/implementations, converge to one modification point
  • Registry instead of if-else: Use registry/plugin tables instead of conditional branch chains
  • Use magic cautiously: Auto-scanning and dynamic imports need to evaluate readability and debuggability

3. 构建模式

3. Construction Patterns

  • 避免半成品对象:不推荐"实例化后加载";使用
    classmethod
    构建
  • 多源多入口:env/file/显式使用不同的构建入口,不在
    __init__
    用标志
  • 减少导入负担:不暴露不必要的命名到包顶层
  • Avoid semi-finished objects: Do not recommend "instantiate then load"; use
    classmethod
    for construction
  • Multiple sources and entry points: Use different construction entries for env/file/explicit scenarios, do not use flags in
    __init__
  • Reduce import burden: Do not expose unnecessary names to the package top level

4. 生态扩展

4. Ecosystem Expansion

  • 使用扩展点:hook、adapter、auth、middleware
  • 避免猴子补丁:改用注册、协议、继承
  • 包装而非重写:扩展功能而非覆盖全部
  • Use extension points: hooks, adapters, auth, middleware
  • Avoid monkey patching: Use registration, protocols, inheritance instead
  • Wrap instead of rewrite: Extend functions instead of overwriting everything

5. 明确性

5. Explicitness

  • 避免 `getattr:优先显式字段和描述符
  • 谨慎使用元类:只在必要时使用
  • 显式优于隐式:优先可读性而非炫技
  • Avoid
    __getattr__
    : Prioritize explicit fields and descriptors
  • Use metaclasses cautiously: Only use when necessary
  • Explicit is better than implicit: Prioritize readability over showing off skills

操作步骤

Operation Steps

┌─────────────────────────────────────────────────────────────┐
│  1. UNDERSTAND: 理解需求与现有代码                          │
├─────────────────────────────────────────────────────────────┤
│  2. ANALYZE: 分析代码风格问题,识别非 Pythonic 模式         │
├─────────────────────────────────────────────────────────────┤
│  3. IMPROVE: 应用 Pythonic 惯用法和设计模式                 │
├─────────────────────────────────────────────────────────────┤
│  4. REVIEW: 根据审查清单检查改进方案                        │
├─────────────────────────────────────────────────────────────┤
│  5. REFINE: 优化细节,提供替代方案和权衡分析                │
└─────────────────────────────────────────────────────────────┘
┌─────────────────────────────────────────────────────────────┐
│  1. UNDERSTAND: Understand requirements and existing code  │
├─────────────────────────────────────────────────────────────┤
│  2. ANALYZE: Analyze code style issues and identify non-Pythonic patterns │
├─────────────────────────────────────────────────────────────┤
│  3. IMPROVE: Apply Pythonic idioms and design patterns     │
├─────────────────────────────────────────────────────────────┤
│  4. REVIEW: Check improvement plans against review checklists │
├─────────────────────────────────────────────────────────────┤
│  5. REFINE: Optimize details and provide alternative solutions and trade-off analysis │
└─────────────────────────────────────────────────────────────┘

标准流程:

Standard Process:

  1. 代码分析
    • 阅读用户提供的代码,识别非 Pythonic 的模式
    • 参考 references/python-rules.md 中的 Python 之禅和规范
    • 关注:命名规范、控制流、数据类型使用、函数设计、异常处理等
  2. Pythonic 改进
    • 根据问题类型选择合适的参考文档
    • 基础改进references/control-flow.mdreferences/data-types.mdreferences/functions.md
    • 高级特性references/decorators.mdreferences/advanced-patterns.md
    • 性能优化references/performance-tips.md
    • 重构指导references/refactoring-guide.md
    • 应用 Pythonic 惯用法:列表推导、生成器、上下文管理器、装饰器等
    • 参考 assets/templates/ 中的标准模板
  3. 代码对比与解释
    • 展示改进前后的代码对比
    • 解释改进的理由和遵循的 Pythonic 原则
    • 说明性能、可读性和维护性的提升
    • 必要时提供替代方案和权衡分析
  4. 最佳实践与进阶建议
    • 根据 references/solid-principles.md 提供设计原则建议
    • 参考 references/edge-cases.md 处理边界情况
    • 提供相关 Pythonic 模式的学习资源和进一步优化方向
  1. Code Analysis
    • Read the code provided by users and identify non-Pythonic patterns
    • Refer to the Zen of Python and specifications in references/python-rules.md
    • Focus on: naming conventions, control flow, data type usage, function design, exception handling, etc.
  2. Pythonic Improvements
    • Select appropriate reference documents based on the type of problem
    • Basic Improvements: references/control-flow.md, references/data-types.md, references/functions.md
    • Advanced Features: references/decorators.md, references/advanced-patterns.md
    • Performance Optimization: references/performance-tips.md
    • Refactoring Guidance: references/refactoring-guide.md
    • Apply Pythonic idioms: list comprehensions, generators, context managers, decorators, etc.
    • Refer to standard templates in assets/templates/
  3. Code Comparison and Explanation
    • Show code comparison before and after improvement
    • Explain the reasons for improvement and the Pythonic principles followed
    • Illustrate improvements in performance, readability, and maintainability
    • Provide alternative solutions and trade-off analysis when necessary
  4. Best Practices and Advanced Suggestions
    • Provide design principle suggestions based on references/solid-principles.md
    • Handle edge cases with reference to references/edge-cases.md
    • Provide learning resources and further optimization directions for related Pythonic patterns

可选分支:

Optional Branches:

  • 基础风格问题:使用基础参考文档提供改进建议
  • 高级特性应用:推荐使用描述符、元类、迭代器协议等高级模式
  • 性能优化需求:结合性能优化参考文档提供建议
  • 重构需求:使用重构指南提供系统性改进方案
  • 代码已经较好:识别可进一步优化的细节,提供高级优化建议
  • Basic Style Issues: Use basic reference documents to provide improvement suggestions
  • Advanced Feature Application: Recommend using advanced patterns such as descriptors, metaclasses, iterator protocols, etc.
  • Performance Optimization Requirements: Combine performance optimization reference documents to provide suggestions
  • Refactoring Requirements: Use refactoring guides to provide systematic improvement plans
  • Code is already good: Identify details that can be further optimized and provide advanced optimization suggestions

审查清单

Review Checklist

使用此清单进行代码审查或自查:
检查项问题
🔧 扩展性新增功能是否只需修改一处代码?
🎯 默认值API 是否有合理的默认值?是否隐藏了不必要的对象?
📈 复杂度复杂度是否遵循"简单到复杂",默认路径是否最轻量?
🔌 扩展点是否优先使用生态系统的扩展点?
👁️ 明确性是否为了炫技而牺牲了明确性和可维护性?
🔄 移植代码移植代码时是否重新设计了调用模式?
Use this checklist for code review or self-check:
Check ItemQuestion
🔧 ExtensibilityDoes adding new features only require modifying one place in the code?
🎯 Default ValuesDoes the API have reasonable default values? Are unnecessary objects hidden?
📈 ComplexityDoes complexity follow "simple to complex", and is the default path the lightest?
🔌 Extension PointsAre ecosystem extension points prioritized?
👁️ ExplicitnessIs explicitness and maintainability sacrificed for showing off skills?
🔄 Ported CodeWas the calling pattern redesigned when porting code?

推荐与避免的模式

Recommended and Avoided Patterns

推荐使用的模式

Recommended Patterns

场景推荐做法
多种实现方式注册表模式 + 装饰器注册
资源管理上下文管理器 (
with
)
多种输入来源
@classmethod
构造器
配置字段描述符 (Descriptor)
扩展第三方库官方扩展点 (hook/adapter/auth)
异步操作async/await + try/except/finally
CLI 工具argparse + Command 类
复杂对象构建Builder 模式
策略选择注册表/字典查找
循环导入延迟导入/重构模块
ScenarioRecommended Practice
Multiple implementation methodsRegistry pattern + decorator registration
Resource managementContext manager (
with
)
Multiple input sources
@classmethod
constructors
Configuration fieldsDescriptors
Extending third-party librariesOfficial extension points (hook/adapter/auth)
Asynchronous operationsasync/await + try/except/finally
CLI toolsargparse + Command class
Complex object constructionBuilder pattern
Strategy selectionRegistry/dictionary lookup
Circular importsLazy import/refactor modules

避免使用的模式

Avoided Patterns

反模式问题
大量 if-else 分支添加功能需要修改多处
__init__
中使用标志控制路径
互斥参数不明确
__getattr__
回退
削弱可发现性和类型检查
过度使用元类污染用户的心智模型
自定义包装回原库属性重复,维护负担
JS 风格的回调不 Pythonic
全局状态难以测试和维护
过度继承组合优于继承
硬编码配置缺乏灵活性
裸 except吞掉所有异常
Anti-PatternProblem
A large number of if-else branchesAdding features requires modifying multiple places
Using flags to control paths in
__init__
Mutually exclusive parameters are unclear
__getattr__
fallback
Weakens discoverability and type checking
Overuse of metaclassesPollutes users' mental models
Custom wrapping of original librariesDuplicate attributes, maintenance burden
JS-style callbacksNot Pythonic
Global stateDifficult to test and maintain
Over-inheritanceComposition over inheritance
Hard-coded configurationLack of flexibility
Bare exceptSwallows all exceptions

响应格式

Response Format

解决代码风格问题时,使用以下格式:
markdown
undefined
When solving code style problems, use the following format:
markdown
undefined

Summary

Summary

[完成的工作总结]
[Summary of completed work]

Changes Made

Changes Made

Design Decisions

Design Decisions

  • [为什么选择某些模式]
  • [Why certain patterns were chosen]

Review Checklist

Review Checklist

  • 单点扩展性
  • 合理默认值
  • 渐进式复杂度
  • 正确使用扩展点
  • 明确性优于魔法
  • Single-point extensibility
  • Reasonable default values
  • Progressive complexity
  • Correct use of extension points
  • Explicitness over magic

Suggestions (if any)

Suggestions (if any)

  • [可以进一步改进的地方]
undefined
  • [Areas for further improvement]
undefined

资源索引

Resource Index

基础参考

Basic References

  • 友好模式:见 references/friendly-patterns.md(Friendly Python 理念、用户友好模式、维护友好模式、构建模式、注册表模式、上下文管理器)
  • Python 规则:见 references/python-rules.md(Python 之禅、PEP 8 规范)
  • 变量命名:见 references/variables-naming.md(命名原则、布尔变量命名、循环变量命名、临时变量)
  • 控制流:见 references/control-flow.md(if-else 优化、卫语句、提前返回、海象运算符、循环优化、match-case)
  • 数字和字符串:见 references/data-types.md(数字操作、字符串处理、格式化、正则表达式、类型转换)
  • 容器类型:见 references/container-types.md(列表、字典、集合、元组最佳实践、推导式、collections 模块)
  • 函数设计:见 references/functions.md(函数设计原则、参数设计、返回值设计、类型提示、高阶函数)
  • 异常处理:见 references/exceptions.md(异常处理最佳实践、上下文管理器)
  • 装饰器:见 references/decorators.md(装饰器深入应用、类装饰器、参数化装饰器)
  • 循环导入:见 references/cyclic-imports.md(循环导入的定义、原因、后果和解决方法)
  • 文件操作:见 references/file-operations.md(文件读写、路径处理、pathlib)
  • Friendly Patterns: See references/friendly-patterns.md (Friendly Python concept, user-friendly patterns, maintainer-friendly patterns, construction patterns, registry patterns, context managers)
  • Python Rules: See references/python-rules.md (Zen of Python, PEP 8 specifications)
  • Variable Naming: See references/variables-naming.md (Naming principles, boolean variable naming, loop variable naming, temporary variables)
  • Control Flow: See references/control-flow.md (if-else optimization, guard clauses, early returns, walrus operator, loop optimization, match-case)
  • Numbers and Strings: See references/data-types.md (Number operations, string processing, formatting, regular expressions, type conversion)
  • Container Types: See references/container-types.md (Best practices for lists, dictionaries, sets, tuples, comprehensions, collections module)
  • Function Design: See references/functions.md (Function design principles, parameter design, return value design, type hints, higher-order functions)
  • Exception Handling: See references/exceptions.md (Best practices for exception handling, context managers)
  • Decorators: See references/decorators.md (In-depth application of decorators, class decorators, parameterized decorators)
  • Cyclic Imports: See references/cyclic-imports.md (Definition, causes, consequences, and solutions for cyclic imports)
  • File Operations: See references/file-operations.md (File reading and writing, path handling, pathlib)

进阶参考

Advanced References

  • SOLID 原则:见 references/solid-principles.md(面向对象设计原则、设计模式)
  • 高级模式:见 references/advanced-patterns.md(元类、描述符、迭代器协议、并发、魔术方法)
  • 性能优化:见 references/performance-tips.md(性能分析、内存优化、计算优化、并发、缓存)
  • 重构指南:见 references/refactoring-guide.md(代码异味、重构技巧、重构模式、重构工具)
  • 边界情况:见 references/edge-cases.md(异常和边界情况处理)
  • SOLID Principles: See references/solid-principles.md (Object-oriented design principles, design patterns)
  • Advanced Patterns: See references/advanced-patterns.md (Metaclasses, descriptors, iterator protocols, concurrency, magic methods)
  • Performance Optimization: See references/performance-tips.md (Performance analysis, memory optimization, computation optimization, concurrency, caching)
  • Refactoring Guide: See references/refactoring-guide.md (Code smells, refactoring techniques, refactoring patterns, refactoring tools)
  • Edge Cases: See references/edge-cases.md (Exception and edge case handling)

代码模板

Code Templates

  • 基础模板:见 assets/templates/naming-patterns.pyassets/templates/control-flow-patterns.pyassets/templates/string-number-operations.pyassets/templates/container-operations.pyassets/templates/exception-handling.py
  • 高级模板:见 assets/templates/advanced-patterns.py(元类、描述符、迭代器、装饰器、并发等高级模式)
  • 性能模板:见 assets/templates/performance-patterns.py(缓存、批处理、惰性求值、并行处理等性能模式)
  • Basic Templates: See assets/templates/naming-patterns.py, assets/templates/control-flow-patterns.py, assets/templates/string-number-operations.py, assets/templates/container-operations.py, assets/templates/exception-handling.py
  • Advanced Templates: See assets/templates/advanced-patterns.py (Advanced patterns such as metaclasses, descriptors, iterators, decorators, concurrency, etc.)
  • Performance Templates: See assets/templates/performance-patterns.py (Performance patterns such as caching, batching, lazy evaluation, parallel processing, etc.)

核心原则

Core Principles

基于 Python 之禅和 Friendly Python 的核心价值观:
  • 优美胜于丑陋:优先选择简洁、优雅的解决方案
  • 明了胜于晦涩:代码应该清晰易懂,避免过度设计
  • 简洁胜于复杂:用最少的代码完成任务,避免不必要的复杂性
  • 复杂胜于凌乱:使用有组织的复杂结构,而非混乱的代码
  • 扁平胜于嵌套:减少嵌套层级,提高代码可读性
  • 间隔胜于紧凑:合理的空行和空格,让代码更易读
  • 可读性很重要:代码是给人读的,清晰度优先
  • 实用性胜于纯粹性:考虑实际应用场景和性能需求
  • 用户友好 + 维护友好:API 易于使用,代码易于维护
Based on the Zen of Python and core values of Friendly Python:
  • Beautiful is better than ugly: Prioritize concise and elegant solutions
  • Explicit is better than implicit: Code should be clear and easy to understand, avoid over-design
  • Simple is better than complex: Use minimal code to complete tasks, avoid unnecessary complexity
  • Complex is better than complicated: Use organized complex structures instead of messy code
  • Flat is better than nested: Reduce nesting levels to improve code readability
  • Sparse is better than dense: Reasonable blank lines and spaces make code easier to read
  • Readability counts: Code is for people to read, clarity comes first
  • Special cases aren't special enough to break the rules: But practicality beats purity
  • User-Friendly + Maintainer-Friendly: APIs are easy to use, code is easy to maintain

实现方式说明

Implementation Instructions

本 Skill 的所有功能由智能体通过自然语言指导完成,无需脚本执行:
  • 代码分析与改进:智能体直接分析代码并提供 Pythonic 改进建议
  • 模板推荐:从
    assets/templates/
    中选择合适的模板并展示使用方法
  • 最佳实践指导:基于参考文档提供详细的指导和示例
All functions of this Skill are completed by the agent through natural language guidance, no script execution required:
  • Code Analysis and Improvement: The agent directly analyzes code and provides Pythonic improvement suggestions
  • Template Recommendation: Select appropriate templates from
    assets/templates/
    and demonstrate usage methods
  • Best Practice Guidance: Provide detailed guidance and examples based on reference documents

使用示例

Usage Examples

示例 1:友好模式应用

Example 1: Friendly Pattern Application

  • 功能说明:应用注册表模式替代 if-else 分支,提高代码可扩展性
  • 执行方式:分析现有代码结构,重构为注册表模式
  • 参考文档references/friendly-patterns.md
  • 关键要点
    • 识别大量 if-else 分支
    • 使用注册表装饰器替代条件链
    • 新增功能只需注册,无需修改核心代码
    • 保持代码的可读性和可维护性
  • Function Description: Apply registry pattern to replace if-else branches and improve code extensibility
  • Execution Method: Analyze existing code structure and refactor to registry pattern
  • Reference Document: references/friendly-patterns.md
  • Key Points:
    • Identify a large number of if-else branches
    • Use registry decorators to replace conditional chains
    • Adding new features only requires registration, no need to modify core code
    • Maintain code readability and maintainability

示例 2:基础循环改进

Example 2: Basic Loop Improvement

  • 功能说明:将传统的 for 循环转换为列表推导或生成器表达式
  • 执行方式:智能体分析代码并提供改进建议
  • 参考文档references/control-flow.md
  • 关键要点
    • 识别可转换的循环模式
    • 使用列表推导简化代码
    • 使用生成器表达式处理大数据
    • 保持代码可读性
  • Function Description: Convert traditional for loops to list comprehensions or generator expressions
  • Execution Method: The agent analyzes code and provides improvement suggestions
  • Reference Document: references/control-flow.md
  • Key Points:
    • Identify convertible loop patterns
    • Use list comprehensions to simplify code
    • Use generator expressions for large data
    • Maintain code readability

示例 2:命名规范优化

Example 2: Naming Convention Optimization

  • 功能说明:改进变量、函数、类的命名
  • 执行方式:提供更清晰、更具描述性的命名建议
  • 参考文档references/variables-naming.md
  • 模板参考assets/templates/naming-patterns.py
  • 关键要点
    • 使用有意义的名称
    • 遵循命名约定(snake_case、CamelCase)
    • 避免缩写和歧义
    • 使用动词命名函数,名词命名类
  • Function Description: Improve naming of variables, functions, and classes
  • Execution Method: Provide clearer and more descriptive naming suggestions
  • Reference Document: references/variables-naming.md
  • Template Reference: assets/templates/naming-patterns.py
  • Key Points:
    • Use meaningful names
    • Follow naming conventions (snake_case, CamelCase)
    • Avoid abbreviations and ambiguities
    • Use verbs for function names, nouns for class names

示例 3:异常处理改进

Example 3: Exception Handling Improvement

  • 功能说明:改进异常处理方式和资源管理
  • 执行方式:推荐使用更 Python 的异常处理模式
  • 参考文档references/exceptions.md
  • 模板参考assets/templates/exception-handling.py
  • 关键要点
    • 捕获特定的异常类型
    • 使用上下文管理器管理资源
    • 提供有用的错误消息
    • 避免裸 except
  • Function Description: Improve exception handling methods and resource management
  • Execution Method: Recommend more Pythonic exception handling patterns
  • Reference Document: references/exceptions.md
  • Template Reference: assets/templates/exception-handling.py
  • Key Points:
    • Catch specific exception types
    • Use context managers to manage resources
    • Provide useful error messages
    • Avoid bare except

示例 4:函数设计优化

Example 4: Function Design Optimization

  • 功能说明:优化函数设计和参数传递
  • 执行方式:提供函数重写建议
  • 参考文档references/functions.md
  • 关键要点
    • 遵循单一职责原则
    • 合理使用默认参数和可变参数
    • 使用类型提示提高可读性
    • 返回一致的结果类型
  • Function Description: Optimize function design and parameter passing
  • Execution Method: Provide function rewriting suggestions
  • Reference Document: references/functions.md
  • Key Points:
    • Follow single responsibility principle
    • Use default parameters and variable parameters reasonably
    • Use type hints to improve readability
    • Return consistent result types

示例 5:高级模式应用

Example 5: Advanced Pattern Application

  • 功能说明:应用元类、描述符、迭代器协议等高级模式
  • 执行方式:分析需求并推荐合适的高级模式
  • 参考文档references/advanced-patterns.md
  • 模板参考assets/templates/advanced-patterns.py
  • 关键要点
    • 理解适用场景和权衡
    • 正确实现协议和魔术方法
    • 保持代码可读性和可维护性
    • 避免过度设计
  • Function Description: Apply advanced patterns such as metaclasses, descriptors, iterator protocols, etc.
  • Execution Method: Analyze requirements and recommend appropriate advanced patterns
  • Reference Document: references/advanced-patterns.md
  • Template Reference: assets/templates/advanced-patterns.py
  • Key Points:
    • Understand applicable scenarios and trade-offs
    • Correctly implement protocols and magic methods
    • Maintain code readability and maintainability
    • Avoid over-design

示例 6:性能优化

Example 6: Performance Optimization

  • 功能说明:提供性能优化建议
  • 执行方式:分析代码并提供优化方案
  • 参考文档references/performance-tips.md
  • 模板参考assets/templates/performance-patterns.py
  • 关键要点
    • 使用性能分析工具识别瓶颈
    • 选择合适的数据结构和算法
    • 使用缓存和批处理
    • 考虑并发和异步处理
  • Function Description: Provide performance optimization suggestions
  • Execution Method: Analyze code and provide optimization solutions
  • Reference Document: references/performance-tips.md
  • Template Reference: assets/templates/performance-patterns.py
  • Key Points:
    • Use performance analysis tools to identify bottlenecks
    • Select appropriate data structures and algorithms
    • Use caching and batching
    • Consider concurrency and asynchronous processing

示例 7:代码重构

Example 7: Code Refactoring

  • 功能说明:系统性地改进代码结构和质量
  • 执行方式:提供重构方案和步骤
  • 参考文档references/refactoring-guide.md
  • 关键要点
    • 识别代码异味
    • 小步重构,保持测试通过
    • 提取方法和类,减少重复
    • 简化条件和复杂逻辑
  • Function Description: Systematically improve code structure and quality
  • Execution Method: Provide refactoring plans and steps
  • Reference Document: references/refactoring-guide.md
  • Key Points:
    • Identify code smells
    • Refactor in small steps, keep tests passing
    • Extract methods and classes to reduce duplication
    • Simplify conditions and complex logic

注意事项

Notes

  • 优先使用 Python 内置功能和标准库,避免重复造轮子
  • Pythonic 不等于最简代码,要在简洁和可读性之间平衡
  • 遵循 PEP 8 代码风格规范
  • 充分利用 Python 的动态特性和语法糖
  • 考虑代码的性能和维护性,避免过度优化
  • 理解 SOLID 原则,编写可维护的面向对象代码
  • 正确处理边界情况和异常
  • 高级模式使用时考虑适用场景和可维护性
  • 性能优化前先测量,避免过早优化
  • 重构时保持测试通过,逐步改进
  • 遵循 "用户友好 + 维护友好" 的设计理念
  • 使用审查清单确保代码质量
  • 优先选择推荐模式,避免反模式
  • Prioritize using Python built-in functions and standard libraries, avoid reinventing the wheel
  • Pythonic does not mean the shortest code, balance conciseness and readability
  • Follow PEP 8 code style specifications
  • Make full use of Python's dynamic features and syntactic sugar
  • Consider code performance and maintainability, avoid over-optimization
  • Understand SOLID principles and write maintainable object-oriented code
  • Correctly handle edge cases and exceptions
  • Consider applicable scenarios and maintainability when using advanced patterns
  • Measure before performance optimization, avoid premature optimization
  • Keep tests passing during refactoring, improve gradually
  • Follow the "User-Friendly + Maintainer-Friendly" design concept
  • Use review checklists to ensure code quality
  • Prioritize recommended patterns and avoid anti-patterns