
python-standards
Python 开发规范检查:遵循 PEP 8、PEP 257 和 Python 最佳实践,包括代码审查、类型提示和文档字符串检查
- version
- 1.0.0
Install
/plugin install python-standards@260112-cc-plugins-studyRun it inside Claude Code after adding the marketplace with /plugin marketplace add lwmacct/260112-cc-plugins-study.
Contents
Discovered from sourceCommands 3
Check Python docstrings for completeness and style (PEP 257):
Docstring Checks:
-
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
-
Style Guide (Choose one convention per project)
- Google Style (Recommended for readability)
- NumPy Style (Good for scientific code)
- reStructuredText (Sphinx default)
-
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. """ ... -
One-Line Docstrings
def foo() -> None: """Do something simple.""" pass- Closing quotes on same line
- Complete sentence with period
- Imperative mood ("Do", not "Does")
-
Module-Level Docstrings
""" This module provides utilities for data processing. It includes functions for: - Reading CSV files - Cleaning data - Exporting to various formats """ -
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. """ -
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
-
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:
-
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
-
Naming Conventions (PEP 8)
snake_casefor functions, variables, and module namesPascalCase(CapWords) for classesUPPER_CASEfor constants_leading_underscorefor "internal" use__dunder__for magic methods only
-
Type Hints (PEP 484)
- All public functions should have type hints
- Use
typingmodule for complex types (List,Dict,Optional, etc.) - Return type should always be specified
- Use
from __future__ import annotationsfor forward references
-
Error Handling
- Catch specific exceptions, not bare
except: - Use
finallyfor cleanup code - Include error context in messages
- Prefer exception chaining (
raise ... from e)
- Catch specific exceptions, not bare
-
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
-
Pythonic Idioms
- Use list comprehensions instead of
map/filterwith lambda - Use
withstatements for resource management - Use
enumerate()instead of manual index tracking - Use context managers (
@contextmanagerwhen appropriate) - Prefer dataclasses over
__init__boilerplate - Use f-strings for formatting (Python 3.6+)
- Use list comprehensions instead of
-
Security Issues
- Avoid
eval()andexec()on user input - Use
subprocess.run()instead ofos.system() - Sanitize input for SQL queries (use parameterized queries)
- Check for hardcoded secrets/credentials
- Avoid
-
Common Anti-patterns
- Using mutable default arguments (
def foo(x=[])) - Not closing files/connections properly
- Overusing
*imports (from module import *) - Redundant parentheses in conditions
- Using mutable default arguments (
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:
-
Function Annotations
- All functions should have parameter type hints
- Return type should always be specified (use
-> Noneexplicitly) - Use
typingmodule for complex types
-
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: ... -
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: ... -
Class Attributes
- Use class-level annotations for attributes
- Consider
dataclassesfor data-heavy classes - Use
@propertywith type hints
-
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: ... -
Type Checking Tools
- Mention
mypyfor static type checking - Use
pyrightorpyreas alternatives - Enable strict mode for better coverage
- Mention
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