Python 开发规范检查:遵循 PEP 8、PEP 257 和 Python 最佳实践,包括代码审查、类型提示和文档字符串检查

version
1.0.0

Install

/plugin install python-standards@260112-cc-plugins-study

Run it inside Claude Code after adding the marketplace with /plugin marketplace add lwmacct/260112-cc-plugins-study.

Contents

Discovered from source

Commands 3

Check Python docstrings for completeness and style (PEP 257):

Docstring Checks:

  1. Presence Check

    • All public modules, classes, functions, and methods should have docstrings
    • Docstrings should be the first statement in the definition
    • Use triple double quotes ("""), not single quotes
  2. Style Guide (Choose one convention per project)

    • Google Style (Recommended for readability)
    • NumPy Style (Good for scientific code)
    • reStructuredText (Sphinx default)
  3. Google Style Examples

    def calculate_distance(point1: tuple[float, float],
                          point2: tuple[float, float]) -> float:
        """Calculate the Euclidean distance between two points.
    
        Args:
            point1: The first (x, y) coordinate pair.
            point2: The second (x, y) coordinate pair.
    
        Returns:
            The distance between the two points.
    
        Raises:
            ValueError: If either point is not a 2D coordinate.
        """
        ...
    
  4. One-Line Docstrings

    def foo() -> None:
        """Do something simple."""
        pass
    
    • Closing quotes on same line
    • Complete sentence with period
    • Imperative mood ("Do", not "Does")
  5. Module-Level Docstrings

    """
    This module provides utilities for data processing.
    
    It includes functions for:
    - Reading CSV files
    - Cleaning data
    - Exporting to various formats
    """
    
  6. Class Docstrings

    class DataProcessor:
        """Process and transform data.
    
        This class handles various data transformation operations
        including filtering, aggregation, and formatting.
    
        Attributes:
            data: The input dataset to process.
            config: Configuration options for processing.
        """
    
  7. Common Issues

    • ❌ Missing docstring on public API
    • ❌ Inconsistent style within project
    • ❌ Not documenting parameters or return values
    • ❌ Missing Raises section for exceptions
    • ❌ Copy-pasted docstrings that don't match implementation
  8. What to Document

    • Functions: What it does, parameters, return value, exceptions raised
    • Classes: Purpose and usage, important attributes
    • Methods: Behavior, parameters, return value
    • Modules: Purpose and main components

Don't Document:

  • Private methods/functions (unless complex)
  • Obvious implementation details
  • Properties if they're simple getters/setters

Output Format:

🔴 MISSING: [Docstring required]
   Location: [file:line]
   Entity: [Function/Class/Module name]
   Fix: [Add docstring with example]

🟡 INCOMPLETE: [Docstring missing information]
   Location: [file:line]
   Missing: [What's missing - e.g., 'Args section', 'Returns', 'Raises']
   Fix: [Complete the docstring]

⚠️ INCONSISTENT: [Style mismatch]
   Location: [file:line]
   Issue: [Style inconsistency description]
   Fix: [Align with project convention]

Ensure all public APIs have clear, complete docstrings.

Review the selected Python code according to PEP 8 and Python best practices:

Check for:

  1. PEP 8 Compliance

    • Maximum line length of 79 characters (or 99 for modern projects)
    • Import order: standard library, third-party, local
    • Two blank lines before functions/classes, one before methods
    • Spaces around operators (except after opening parenthesis)
    • No trailing whitespace
  2. Naming Conventions (PEP 8)

    • snake_case for functions, variables, and module names
    • PascalCase (CapWords) for classes
    • UPPER_CASE for constants
    • _leading_underscore for "internal" use
    • __dunder__ for magic methods only
  3. Type Hints (PEP 484)

    • All public functions should have type hints
    • Use typing module for complex types (List, Dict, Optional, etc.)
    • Return type should always be specified
    • Use from __future__ import annotations for forward references
  4. Error Handling

    • Catch specific exceptions, not bare except:
    • Use finally for cleanup code
    • Include error context in messages
    • Prefer exception chaining (raise ... from e)
  5. Code Organization

    • One class per file (usually)
    • Keep functions focused and small (< 50 lines)
    • Use docstrings (Google, NumPy, or reStructuredText style)
    • Group related code together
  6. Pythonic Idioms

    • Use list comprehensions instead of map/filter with lambda
    • Use with statements for resource management
    • Use enumerate() instead of manual index tracking
    • Use context managers (@contextmanager when appropriate)
    • Prefer dataclasses over __init__ boilerplate
    • Use f-strings for formatting (Python 3.6+)
  7. Security Issues

    • Avoid eval() and exec() on user input
    • Use subprocess.run() instead of os.system()
    • Sanitize input for SQL queries (use parameterized queries)
    • Check for hardcoded secrets/credentials
  8. Common Anti-patterns

    • Using mutable default arguments (def foo(x=[]))
    • Not closing files/connections properly
    • Overusing * imports (from module import *)
    • Redundant parentheses in conditions

Provide feedback in this format:

❌ PEP8: [Violation description]
   Location: [file:line]
   Why: [Explanation of guideline]
   Fix: [Suggested fix with example]

⚠️ PEP 257: [Docstring issue]
   Location: [file:line]
   Fix: [Docstring example]

🔒 SECURITY: [Security concern]
   Location: [file:line]
   Why: [Explanation of risk]
   Fix: [Secure alternative]

Focus on PEP 8 violations first, then quality improvements.

Check Python code for type hint completeness and correctness:

Type Hint Checks:

  1. Function Annotations

    • All functions should have parameter type hints
    • Return type should always be specified (use -> None explicitly)
    • Use typing module for complex types
  2. Common Type Patterns

    # Basic types
    def process(name: str, count: int) -> bool: ...
    
    # Collections
    from typing import List, Dict, Set, Tuple
    def get_items() -> List[str]: ...
    def get_mapping() -> Dict[str, int]: ...
    
    # Optional values
    from typing import Optional
    def find_user(id: int) -> Optional[User]: ...
    
    # Union types
    from typing import Union
    def process(data: Union[str, bytes]) -> str: ...
    
    # Use pipe syntax (Python 3.10+)
    def process(data: str | bytes) -> str: ...
    
  3. Advanced Type Patterns

    # Callable
    from typing import Callable
    def apply(func: Callable[[int, int], int]) -> int: ...
    
    # TypeVar for generic functions
    from typing import TypeVar
    T = TypeVar('T')
    def first(items: List[T]) -> T: ...
    
    # Protocol for structural subtyping
    from typing import Protocol
    class Sized(Protocol):
        def __len__(self) -> int: ...
    
  4. Class Attributes

    • Use class-level annotations for attributes
    • Consider dataclasses for data-heavy classes
    • Use @property with type hints
  5. Common Mistakes

    # ❌ Don't use Any when specific type is known
    def process(x: Any) -> Any: ...
    
    # ❌ Don't forget return type
    def process(x: int): ...
    
    # ❌ Don't use comments for types
    def process(x):  # type: int
        ...
    
    # ✅ Use proper type hints
    def process(x: int) -> int: ...
    
  6. Type Checking Tools

    • Mention mypy for static type checking
    • Use pyright or pyre as alternatives
    • Enable strict mode for better coverage

Output Format:

🔴 MISSING: [Function/Class missing type hints]
   Location: [file:line]
   Fix: [Add proper type hints with example]

🟡 IMPRECISE: [Using Any or generic type]
   Location: [file:line]
   Why: [Specific type is better for documentation and checking]
   Fix: [More precise type hint]

💡 SUGGESTION: [Modern type pattern]
   Location: [file:line]
   Before: [Old pattern]
   After: [Modern alternative]

Check for missing type hints in all public functions and methods.

Sponsors

Details

Marketplace
lwmacct/260112-cc-plugins-study
Source
plugins/python-standards
Author
Claude Code
Category
Development Tools
License
MIT
Keywords
python, pep8, standards, code-review, best-practices, type-hints

More from lwmacct/260112-cc-plugins-study

All 3