Skills Agentes

Python Code Style

Estilo de código Python, linting, formateo, convenciones de nombres y estándares de documentación; útil al escribir código nuevo, revisar estilo, configurar linters o escribir docstrings.

Reemplaza a: flake8, isort y black por separado

Estrellas
39.8k

en todo el repo

Actividad
24

0–100, la ruta de este skill

Actualizado
hace 7 meses

último commit aquí

Commits
0

últimos 90 días

Contexto
2k tok

52 tok en reposo

Paquete
1 archivo

8 KB

Instalar

Funciona con cualquier agente que lea SKILL.md

npx -y skills add wshobson/agents --skill python-code-style --agent claude-code

Se instala solo en este repositorio.

Este skill makes network requests.

Qué hace

  • Configura ruff y mypy/pyright con reglas de lint, formato y tipado estricto en pyproject.toml
  • Aplica convenciones de nombres PEP 8 para archivos, clases, funciones y constantes
  • Organiza imports en orden stdlib/terceros/local usando imports absolutos
  • Genera docstrings estilo Google para funciones, clases y métodos públicos
  • Define estándares de línea (120 caracteres) y estructura de README/CHANGELOG

Úsalo cuando

  • Configurar linting y formateo para un proyecto nuevo
  • Escribir o revisar docstrings
  • Establecer estándares de código del equipo
  • Configurar ruff, mypy o pyright

No lo uses cuando

    Qué lo activa

    Di cualquiera de estas frases y el agente debería cargar este skill.

    • “Configúrame ruff y mypy estrictos en pyproject.toml”
    • “Escribe docstrings estilo Google para esta clase”
    • “Revisa el estilo de este módulo Python”
    • “Establece las convenciones de nombres para este proyecto”

    SKILL.md

    En inglés

    Python Code Style & Documentation

    Consistent code style and clear documentation make codebases maintainable and collaborative. This skill covers modern Python tooling, naming conventions, and documentation standards.

    When to Use This Skill

    • Setting up linting and formatting for a new project
    • Writing or reviewing docstrings
    • Establishing team coding standards
    • Configuring ruff, mypy, or pyright
    • Reviewing code for style consistency
    • Creating project documentation

    Core Concepts

    1. Automated Formatting

    Let tools handle formatting debates. Configure once, enforce automatically.

    2. Consistent Naming

    Follow PEP 8 conventions with meaningful, descriptive names.

    3. Documentation as Code

    Docstrings should be maintained alongside the code they describe.

    4. Type Annotations

    Modern Python code should include type hints for all public APIs.

    Quick Start

    # Install modern tooling
    pip install ruff mypy
    
    # Configure in pyproject.toml
    [tool.ruff]
    line-length = 120
    target-version = "py312"  # Adjust based on your project's minimum Python version
    
    [tool.mypy]
    strict = true
    

    Fundamental Patterns

    Pattern 1: Modern Python Tooling

    Use ruff as an all-in-one linter and formatter. It replaces flake8, isort, and black with a single fast tool.

    # pyproject.toml
    [tool.ruff]
    line-length = 120
    target-version = "py312"  # Adjust based on your project's minimum Python version
    
    [tool.ruff.lint]
    select = [
        "E",    # pycodestyle errors
        "W",    # pycodestyle warnings
        "F",    # pyflakes
        "I",    # isort
        "B",    # flake8-bugbear
        "C4",   # flake8-comprehensions
        "UP",   # pyupgrade
        "SIM",  # flake8-simplify
    ]
    ignore = ["E501"]  # Line length handled by formatter
    
    [tool.ruff.format]
    quote-style = "double"
    indent-style = "space"
    

    Run with:

    ruff check --fix .  # Lint and auto-fix
    ruff format .       # Format code
    

    Pattern 2: Type Checking Configuration

    Configure strict type checking for production code.

    # pyproject.toml
    [tool.mypy]
    python_version = "3.12"
    strict = true
    warn_return_any = true
    warn_unused_ignores = true
    disallow_untyped_defs = true
    disallow_incomplete_defs = true
    
    [[tool.mypy.overrides]]
    module = "tests.*"
    disallow_untyped_defs = false
    

    Alternative: Use pyright for faster checking.

    [tool.pyright]
    pythonVersion = "3.12"
    typeCheckingMode = "strict"
    

    Pattern 3: Naming Conventions

    Follow PEP 8 with emphasis on clarity over brevity.

    Files and Modules:

    # Good: Descriptive snake_case
    user_repository.py
    order_processing.py
    http_client.py
    
    # Avoid: Abbreviations
    usr_repo.py
    ord_proc.py
    http_cli.py
    

    Classes and Functions:

    # Classes: PascalCase
    class UserRepository:
        pass
    
    class HTTPClientFactory:  # Acronyms stay uppercase
        pass
    
    # Functions and variables: snake_case
    def get_user_by_email(email: str) -> User | None:
        retry_count = 3
        max_connections = 100
    

    Constants:

    # Module-level constants: SCREAMING_SNAKE_CASE
    MAX_RETRY_ATTEMPTS = 3
    DEFAULT_TIMEOUT_SECONDS = 30
    API_BASE_URL = "https://api.example.com"
    

    Pattern 4: Import Organization

    Group imports in a consistent order: standard library, third-party, local.

    # Standard library
    import os
    from collections.abc import Callable
    from typing import Any
    
    # Third-party packages
    import httpx
    from pydantic import BaseModel
    from sqlalchemy import Column
    
    # Local imports
    from myproject.models import User
    from myproject.services import UserService
    

    Use absolute imports exclusively:

    # Preferred
    from myproject.utils import retry_decorator
    
    # Avoid relative imports
    from ..utils import retry_decorator
    

    Advanced Patterns

    Pattern 5: Google-Style Docstrings

    Write docstrings for all public classes, methods, and functions.

    Simple Function:

    def get_user(user_id: str) -> User:
        """Retrieve a user by their unique identifier."""
        ...
    

    Complex Function:

    def process_batch(
        items: list[Item],
        max_workers: int = 4,
        on_progress: Callable[[int, int], None] | None = None,
    ) -> BatchResult:
        """Process items concurrently using a worker pool.
    
        Processes each item in the batch using the configured number of
        workers. Progress can be monitored via the optional callback.
    
        Args:
            items: The items to process. Must not be empty.
            max_workers: Maximum concurrent workers. Defaults to 4.
            on_progress: Optional callback receiving (completed, total) counts.
    
        Returns:
            BatchResult containing succeeded items and any failures with
            their associated exceptions.
    
        Raises:
            ValueError: If items is empty.
            ProcessingError: If the batch cannot be processed.
    
        Example:
            >>> result = process_batch(items, max_workers=8)
            >>> print(f"Processed {len(result.succeeded)} items")
        """
        ...
    

    Class Docstring:

    class UserService:
        """Service for managing user operations.
    
        Provides methods for creating, retrieving, updating, and
        deleting users with proper validation and error handling.
    
        Attributes:
            repository: The data access layer for user persistence.
            logger: Logger instance for operation tracking.
    
        Example:
            >>> service = UserService(repository, logger)
            >>> user = service.create_user(CreateUserInput(...))
        """
    
        def __init__(self, repository: UserRepository, logger: Logger) -> None:
            """Initialize the user service.
    
            Args:
                repository: Data access layer for users.
                logger: Logger for tracking operations.
            """
            self.repository = repository
            self.logger = logger
    

    Pattern 6: Line Length and Formatting

    Set line length to 120 characters for modern displays while maintaining readability.

    # Good: Readable line breaks
    def create_user(
        email: str,
        name: str,
        role: UserRole = UserRole.MEMBER,
        notify: bool = True,
    ) -> User:
        ...
    
    # Good: Chain method calls clearly
    result = (
        db.query(User)
        .filter(User.active == True)
        .order_by(User.created_at.desc())
        .limit(10)
        .all()
    )
    
    # Good: Format long strings
    error_message = (
        f"Failed to process user {user_id}: "
        f"received status {response.status_code} "
        f"with body {response.text[:100]}"
    )
    

    Pattern 7: Project Documentation

    README Structure:

    # Project Name
    
    Brief description of what the project does.
    
    ## Installation
    
    \`\`\`bash
    pip install myproject
    \`\`\`
    
    ## Quick Start
    
    \`\`\`python
    from myproject import Client
    
    client = Client(api_key="...")
    result = client.process(data)
    \`\`\`
    
    ## Configuration
    
    Document environment variables and configuration options.
    
    ## Development
    
    \`\`\`bash
    pip install -e ".[dev]"
    pytest
    \`\`\`
    

    CHANGELOG Format (Keep a Changelog):

    # Changelog
    
    ## [Unreleased]
    
    ### Added
    - New feature X
    
    ### Changed
    - Modified behavior of Y
    
    ### Fixed
    - Bug in Z
    

    Best Practices Summary

    1. Use ruff - Single tool for linting and formatting
    2. Enable strict mypy - Catch type errors before runtime
    3. 120 character lines - Modern standard for readability
    4. Descriptive names - Clarity over brevity
    5. Absolute imports - More maintainable than relative
    6. Google-style docstrings - Consistent, readable documentation
    7. Document public APIs - Every public function needs a docstring
    8. Keep docs updated - Treat documentation as code
    9. Automate in CI - Run linters on every commit
    10. Target Python 3.10+ - For new projects, Python 3.12+ is recommended for modern language features

    Reproducido de wshobson/agents bajo licencia MIT. Leer esta página en markdown.

    Archivos

    1 archivo en el paquete. Solo se lee SKILL.md al activarse — las referencias se cargan si el skill decide que las necesita.

    Antes de instalar

    Requiere instalar ruff y mypy (o pyright) vía pip.

    Necesita en el PATH:pippytest

    Detalles

    Creador
    wshobson
    Licencia
    MIT
    Recursos incluidos
    Solo SKILL.md
    Repositorio
    wshobson/agents
    Código fuente
    Ver SKILL.md

    Etiquetas

    Más de wshobson/agents

    Este repo incluye 183 skills. Si instalas uno, normalmente ya tienes los demás. Ver el pack agents entero y su comando de instalación

    Instala y opera Hermes Tweet, un plugin de Hermes Agent para investigar X/Twitter, leer timelines, analizar tweets y ejecutar operaciones privadas o de cambio de estado con aprobación previa.

    Costo de contexto al activarse
    1.4k tok
    Tamaño del paquete
    3 archivos
    Última actualización
    el mes pasado
    redes sociales

    Úsalo para mantener un almacén Markdown de conocimiento donde cada afirmación compilada se rastrea hasta una fuente inmutable y el drift se detecta con git diff sin gastar tokens.

    Costo de contexto al activarse
    1.4k tok
    Tamaño del paquete
    2 archivos
    Última actualización
    hace 24 días
    documentos

    Úsalo al diseñar o revisar un esquema específico de PostgreSQL: buenas prácticas, tipos de datos, indexación, restricciones, patrones de rendimiento y funciones avanzadas.

    Costo de contexto al activarse
    2k tok
    Tamaño del paquete
    2 archivos
    Última actualización
    hace 24 días
    bases de datos

    Úsalo cuando un proyecto guarda su estado en Superself: lee `self context` al iniciar sesión, vincula el trabajo a una work unit, reporta con evidencia y registra decisiones confirmadas.

    Costo de contexto al activarse
    1.3k tok
    Tamaño del paquete
    1 archivo
    Última actualización
    hace 24 días
    productividad

    Úsalo cuando pidan optimizar un prompt, mejorar su rendimiento, diseñar una plantilla, aplicar chain-of-thought, few-shot prompting o técnicas avanzadas de prompt engineering para producción.

    Costo de contexto al activarse
    1.3k tok
    Tamaño del paquete
    10 archivos
    Última actualización
    el mes pasado
    herramientas desarrollo

    Audita y reescribe prosa para que deje de sonar generada por máquina. Incluye modo solo-detección, modo reescritura y modo edición en el lugar, con perfiles opcionales de voz y contexto.”

    Costo de contexto al activarse
    1.9k tok
    Tamaño del paquete
    4 archivos
    Última actualización
    el mes pasado
    redaccion contenido

    Skills relacionados

    Migra de AngularJS a Angular usando modo híbrido, reescritura incremental de componentes y actualización de la inyección de dependencias.

    Costo de contexto al activarse
    1.8k tok
    Tamaño del paquete
    2 archivos
    Última actualización
    hace 4 meses
    herramientas desarrollo

    Implementa patrones de arquitectura backend probados: Clean Architecture, Hexagonal Architecture y Domain-Driven Design, para construir sistemas mantenibles, testeables y escalables.

    Costo de contexto al activarse
    2k tok
    Tamaño del paquete
    3 archivos
    Última actualización
    hace 4 meses
    herramientas desarrollo

    Domina asyncio, programación concurrente y patrones async/await para apps de alto rendimiento con operaciones no bloqueantes.

    Costo de contexto al activarse
    1.9k tok
    Tamaño del paquete
    2 archivos
    Última actualización
    hace 4 meses
    herramientas desarrollo