Saltar al contenido
Skillpedia
Programación general280 mil · #228

python-patterns

Qué hace

Esta guía enseña a escribir código Python que sea claro, eficiente y fácil de entender, siguiendo buenas prácticas. Cubre cómo organizar el código, usar anotaciones de tipo para mayor claridad y manejar los errores de forma inteligente.

Cuándo usarla

  • ✓Cuando escribes código Python nuevo.
  • ✓Cuando revisas el código de otra persona.
  • ✓Cuando quieres mejorar código que ya existe.

Link de la skill

https://github.com/affaan-m/ECC/blob/main/pi/core/skills/python-patterns/SKILL.md

Cópialo y pégalo en tu IA (Claude, ChatGPT o Cursor) pidiéndole que siga las instrucciones.

Cómo usar

La forma más fácil: copia el mensaje y pégalo en tu IA. Ella lee la skill y sigue las instrucciones.

Mensaje listo para pegar

Usa esta skill para ayudarme: https://github.com/affaan-m/ECC/blob/main/pi/core/skills/python-patterns/SKILL.md Lee el archivo SKILL.md de ese link y sigue sus instrucciones en mi tarea.
¿Quieres que tu IA encuentre skills como esta por sí sola?Instala el MCP gratis de Skillpedia: una línea, y busca entre 15.000+ skills antes de cada tarea.Instalar en 1 minuto →

Ejemplo de qué pedirle a la IA

“¿Cómo puedo escribir una función en Python que sea fácil de leer y que devuelva solo los usuarios activos de una lista?”

5 skills nuevas por semana. 1 minuto de lectura.

Cómo funciona

Muestra ejemplos de código bueno y malo para ilustrar los principios. Explica cómo usar las 'anotaciones de tipo' para indicar qué tipo de datos se espera y cómo usar los 'gestores de contexto' para manejar recursos como los archivos.

Contenido técnico (SKILL.md original)

Texto original del autor, en inglés, directo de GitHub.

Python Development Patterns

Idiomatic Python patterns and best practices for building robust, efficient, and maintainable applications.

When to Activate

  • Writing new Python code
  • Reviewing Python code
  • Refactoring existing Python code
  • Designing Python packages/modules

Core Principles

1. Readability Counts

Python prioritizes readability. Code should be obvious and easy to understand.

# Good: Clear and readable
def get_active_users(users: list[User]) -> list[User]:
    """Return only active users from the provided list."""
    return [user for user in users if user.is_active]


# Bad: Clever but confusing
def get_active_users(u):
    return [x for x in u if x.a]

2. Explicit is Better Than Implicit

Avoid magic; be clear about what your code does.

# Good: Explicit configuration
import logging

logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)

# Bad: Hidden side effects
import some_module
some_module.setup()  # What does this do?

3. EAFP - Easier to Ask Forgiveness Than Permission

Python prefers exception handling over checking conditions.

# Good: EAFP style
def get_value(dictionary: dict, key: str, default_value: Any = None) -> Any:
    try:
        return dictionary[key]
    except KeyError:
        return default_value

# Bad: LBYL (Look Before You Leap) style
def get_value(dictionary: dict, key: str, default_value: Any = None) -> Any:
    if key in dictionary:
        return dictionary[key]
    else:
        return default_value

Type Hints

Basic Type Annotations

from typing import Optional, List, Dict, Any

def process_user(
    user_id: str,
    data: Dict[str, Any],
    active: bool = True
) -> Optional[User]:
    """Process a user and return the updated User or None."""
    if not active:
        return None
    return User(user_id, data)

Modern Type Hints (Python 3.9+)

# Python 3.9+ - Use built-in types
def process_items(items: list[str]) -> dict[str, int]:
    return {item: len(item) for item in items}

# Python 3.8 and earlier - Use typing module
from typing import List, Dict

def process_items(items: List[str]) -> Dict[str, int]:
    return {item: len(item) for item in items}

Type Aliases and TypeVar

from typing import TypeVar, Union

# Type alias for complex types
JSON = Union[dict[str, Any], list[Any], str, int, float, bool, None]

def parse_json(data: str) -> JSON:
    return json.loads(data)

# Generic types
T = TypeVar('T')

def first(items: list[T]) -> T | None:
    """Return the first item or None if list is empty."""
    return items[0] if items else None

Protocol-Based Duck Typing

from typing import Protocol

class Renderable(Protocol):
    def render(self) -> str:
        """Render the object to a string."""

def render_all(items: list[Renderable]) -> str:
    """Render all items that implement the Renderable protocol."""
    return "\n".join(item.render() for item in items)

Error Handling Patterns

Specific Exception Handling

# Good: Catch specific exceptions
def load_config(path: str) -> Config:
    try:
        with open(path) as f:
            return Config.from_json(f.read())
    except FileNotFoundError as e:
        raise ConfigError(f"Config file not found: {path}") from e
    except json.JSONDecodeError as e:
        raise ConfigError(f"Invalid JSON in config: {path}") from e

# Bad: Bare except
def load_config(path: str) -> Config:
    try:
        with open(path) as f:
            return Config.from_json(f.read())
    except:
        return None  # Silent failure!

Exception Chaining

def process_data(data: str) -> Result:
    try:
        parsed = json.loads(data)
    except json.JSONDecodeError as e:
        # Chain exceptions to preserve the traceback
        raise ValueError(f"Failed to parse data: {data}") from e

Custom Exception Hierarchy

class AppError(Exception):
    """Base exception for all application errors."""
    pass

class ValidationError(AppError):
    """Raised when input validation fails."""
    pass

class NotFoundError(AppError):
    """Raised when a requested resource is not found."""
    pass

# Usage
def get_user(user_id: str) -> User:
    user = db.find_user(user_id)
    if not user:
        raise NotFoundError(f"User not found: {user_id}")
    return user

Context Managers

…

Preguntas frecuentes

¿Qué son las 'anotaciones de tipo'?

Las 'anotaciones de tipo' son indicaciones en el código que dicen qué tipo de información espera una variable o función (por ejemplo, texto o número) y qué tipo devuelve. Ayudan a prevenir errores y hacen el código más fácil de entender.

¿Qué significa 'EAFP'?

'EAFP' son las siglas de 'Easier to Ask Forgiveness Than Permission', que en español significa 'es más fácil pedir perdón que pedir permiso'. En programación, significa que es mejor intentar hacer algo y manejar el error si ocurre, en lugar de comprobar todas las condiciones posibles antes de intentarlo.

¿Qué son los 'gestores de contexto'?

Los 'gestores de contexto' son herramientas que ayudan a manejar recursos, como abrir y cerrar archivos automáticamente. Se encargan de liberar los recursos correctamente, incluso si ocurren errores.

Detalles

Descripción original del autor

Pythonic idioms, PEP 8 standards, type hints, and best practices for building robust, efficient, and maintainable Python applications. Use when writing or reviewing Python code and idiomatic structure, typing, or PEP 8 is in question.

repo: affaan-m/ECC

Popularidad

Estrellas en GitHub
280 mil
Posición en el ranking
#228
Licencia
MIT
Actualizada
15/10/2026

¿Te sirve esta skill?

0

Entra para votar.

Comentarios

  • …

Más skills de este repositorio

Skills parecidas