SuperAPI AI Directory

pythonic-style

Coding & development

View repository

Updated 10-16 01:19

About this skill

Pythonic Code Style

Task Objectives

  • This Skill is used to: analyze and improve Python code style so that it better conforms to 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 process
    • Practical templates: provides directly usable code templates (140+)
  • Trigger conditions:

    • The user shows code and requests "how to implement it in a more Pythonic way"
    • The user asks "whether this code is Pythonic"
    • The user needs code review and style improvement suggestions
    • The user asks about best practices for Python-specific syntax
    • The user needs performance optimization or refactoring suggestions
    • The user requests advanced Python patterns or design patterns

Core Philosophy

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│
└────────────────────────────────┴─────────────────────────┘

Design Principles

1. User-Friendly

  • Provide reasonable defaults: make quick start possible without reading documentation
  • Minimum required parameters: hide complex object assembly
  • Transparent resource management: use context managers or a unified entry point
  • Simple to complex: the simple path is the default, and complex requirements can be explicitly extended

2. Maintainer-Friendly

  • Single point of modification: when adding new strategies/commands/implementations, converge to one modification point
  • Registry instead of if-else: use a registry/plugin table instead of conditional branch chains
  • Use magic cautiously: automatic scanning and dynamic imports require evaluating readability and debuggability

3. Construction Patterns

  • Avoid half-finished objects: "instantiate then load" is not recommended; use classmethod construction
  • Multiple sources and multiple entry points: env/file/explicit use different construction entry points, not in __init__ using flags
  • Reduce import burden: do not expose unnecessary names at the package top level

4. Ecosystem Extension

  • Use extension points:hook、adapter、auth、middleware
  • Avoid monkey patching: switch to registration, protocols, inheritance
  • Wrap rather than rewrite: extend functionality rather than overriding everything

5. Explicitness

  • Avoid `getattr: prefer explicit fields and descriptors
  • Use metaclasses cautiously: Use only when necessary
  • Explicit is better than implicit: Prioritize readability over showing off

Procedure

┌─────────────────────────────────────────────────────────────┐
│  1. UNDERSTAND: 理解需求与现有代码                          │
├─────────────────────────────────────────────────────────────┤
│  2. ANALYZE: 分析代码风格问题,识别非 Pythonic 模式         │
├─────────────────────────────────────────────────────────────┤
│  3. IMPROVE: 应用 Pythonic 惯用法和设计模式                 │
├─────────────────────────────────────────────────────────────┤
│  4. REVIEW: 根据审查清单检查改进方案                        │
├─────────────────────────────────────────────────────────────┤
│  5. REFINE: 优化细节,提供替代方案和权衡分析                │
└─────────────────────────────────────────────────────────────┘

Standard process:

  1. Code analysis

    • Read the code provided by the user and identify non-Pythonic patterns
    • Refer to references/python-rules.md the Zen of Python and conventions in
    • Focus on: naming conventions, control flow, data type usage, function design, exception handling, etc.
  2. Pythonic improvements

  3. Code comparison and explanation

    • Show a before-and-after code comparison
    • Explain the reasons for the improvements and the Pythonic principles followed
    • Explain the improvements in performance, readability, and maintainability
    • Provide alternatives and trade-off analysis when necessary
  4. Best practices and advanced suggestions

Optional branches:

  • Basic style issues: Use the basic reference documentation to provide improvement suggestions
  • Advanced feature application: Recommend advanced patterns such as descriptors, metaclasses, iterator protocols, etc.
  • Performance optimization needs: Provide suggestions in conjunction with the performance optimization reference documentation
  • Refactoring needs: Use the refactoring guide to provide systematic improvement plans
  • The code is already fairly good: Identify details that can be further optimized and provide advanced optimization suggestions

Review checklist

Use this checklist for code review or self-check:

Check item Question
🔧 Extensibility Does adding a new feature require modifying code in only one place?
🎯 Default values Does the API have reasonable default values? Does it hide unnecessary objects?
📈 Complexity Does the complexity follow "simple to complex", and is the default path the lightest?
🔌 Extension points Are the ecosystem's extension points prioritized?
👁️ Clarity Has clarity and maintainability been sacrificed for showing off?
🔄 Porting code When porting code, has the calling pattern been redesigned?

Recommended and avoided patterns

Recommended patterns

Scenario Recommended practice
Multiple implementation methods Registry pattern + decorator registration
Resource management Context manager (with)
Multiple input sources @classmethod constructor
Configuration fields Descriptor
Extending third-party libraries Official extension points (hook/adapter/auth)
Asynchronous operations async/await + try/except/finally
CLI tools argparse + Command class
Complex object construction Builder pattern
Strategy selection Registry/dictionary lookup
Circular imports Deferred imports/module refactoring

Patterns to avoid

Anti-pattern Problem
Large number of if-else branches Adding features requires modifying multiple places
__init__ Use flags to control paths in Mutually exclusive parameters are unclear
__getattr__ fallback Weakens discoverability and type checking
Overuse of metaclasses Pollutes users' mental model
Custom wrapper around the original library Duplicated attributes, maintenance burden
JS-style callbacks Not Pythonic
Global state Hard to test and maintain
Overuse of inheritance Composition over inheritance
Hard-coded configuration Lack of flexibility
Bare except Swallows all exceptions

Response format

When resolving code style issues, use the following format:

## Summary
[完成的工作总结]

## Changes Made
- [改进点 1]: [说明]
- [改进点 2]: [说明]

## Design Decisions
- [为什么选择某些模式]

## Review Checklist
- [x] 单点扩展性
- [x] 合理默认值
- [x] 渐进式复杂度
- [x] 正确使用扩展点
- [x] 明确性优于魔法

## Suggestions (if any)
- [可以进一步改进的地方]

Resource index

Basic reference

Advanced reference

Code Templates

Core Principles

Based on the core values of the Zen of Python and Friendly Python:

  • Beautiful is better than ugly: Prefer concise, elegant solutions
  • Explicit is better than implicit: Code should be clear and easy to understand, avoiding over-engineering
  • Simple is better than complex: Accomplish the task with the least code, avoiding unnecessary complexity
  • Complex is better than complicated: Use organized complex structures rather than chaotic 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 more readable
  • Readability counts: Code is meant to be read by people, clarity comes first
  • Practicality beats purity: Consider actual application scenarios and performance requirements
  • User-friendly + Maintenance-friendly: APIs are easy to use, code is easy to maintain

Implementation Notes

All functions of this Skill are completed by the agent through natural language guidance, with no script execution required:

  • Code Analysis and Improvement: The agent directly analyzes code and provides Pythonic improvement suggestions
  • Template Recommendation: From assets/templates/ select an appropriate template and demonstrate how to use it
  • Best Practice Guidance: Provide detailed guidance and examples based on reference documentation

Usage Examples

Example 1: Friendly Pattern Application

  • Function Description: Apply the registry pattern to replace if-else branches and improve code extensibility
  • Execution Method: Analyze the existing code structure and refactor it into the registry pattern
  • Reference Documentation:references/friendly-patterns.md
  • Key Points:
    • Identify a large number of if-else branches
    • Use registry decorators to replace conditional chains
    • New features only need to be registered, without modifying the core code
    • Maintain code readability and maintainability

Example 2: Basic Loop Improvement

  • Function Description: Convert traditional for loops into list comprehensions or generator expressions
  • Execution Method: The agent analyzes the code and provides improvement suggestions
  • Reference Documentation:references/control-flow.md
  • Key Points:
    • Identify convertible loop patterns
    • Simplify code using list comprehensions
    • Use generator expressions to handle large data
    • Maintain code readability

Example 2: Naming convention optimization

  • Function description: Improve the naming of variables, functions, and classes
  • Execution method: Provide clearer and more descriptive naming suggestions
  • Reference documentation: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 ambiguity
    • Use verbs to name functions and nouns to name classes

Example 3: Exception handling improvement

  • Function description: Improve exception handling and resource management
  • Execution method: Recommend more Pythonic exception handling patterns
  • Reference documentation: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

Example 4: Function design optimization

  • Function description: Optimize function design and parameter passing
  • Execution method: Provide function rewrite suggestions
  • Reference documentation:references/functions.md
  • Key points:
    • Follow the single responsibility principle
    • Use default parameters and variadic parameters appropriately
    • Use type hints to improve readability
    • Return consistent result types

Example 5: Advanced pattern application

  • Function description: Apply advanced patterns such as metaclasses, descriptors, and the iterator protocol
  • Execution method: Analyze requirements and recommend suitable advanced patterns
  • Reference documentation: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-engineering

Example 6: Performance optimization

  • Function description: Provide performance optimization suggestions
  • Execution method: Analyze code and provide optimization solutions
  • Reference documentation:references/performance-tips.md
  • Template reference:assets/templates/performance-patterns.py
  • Key points:
    • Use performance analysis tools to identify bottlenecks
    • Choose appropriate data structures and algorithms
    • Use caching and batch processing
    • Consider concurrency and asynchronous processing

Example 7: Code refactoring

  • Function description: Systematically improve code structure and quality
  • Execution method: Provide refactoring plans and steps
  • Reference documentation:references/refactoring-guide.md
  • Key points:
    • Identify code smells
    • Refactor in small steps and keep tests passing
    • Extract methods and classes to reduce duplication
    • Simplify conditions and complex logic

Notes

  • Prefer Python built-in features and the standard library, and avoid reinventing the wheel
  • Pythonic does not mean the simplest code; balance conciseness and readability
  • Follow the PEP 8 code style guidelines
  • Make full use of Python's dynamic features and syntactic sugar
  • Consider code performance and maintainability, and avoid over-optimization
  • Understand the SOLID principles and write maintainable object-oriented code
  • Correctly handle edge cases and exceptions
  • When using advanced patterns, consider the applicable scenarios and maintainability
  • Measure before performance optimization, and avoid premature optimization
  • Keep tests passing during refactoring, and improve gradually
  • Follow the design philosophy of "user-friendly + maintenance-friendly"
  • Use review checklists to ensure code quality
  • Prefer recommended patterns and avoid anti-patterns