Logo di Python Patterns

Python Patterns

Organizzazione
cosmicstack-labs
python-patterns

Python best practices including type hints, async patterns, testing, and project structure

Panoramica

Pubblicato dacosmicstack-labs
Repositorymercury-agent-skills
Nome della skillpython-patterns
Stelle
485
Fork
63
File inclusi
Solo istruzioni
LicenzaMIT
Link
  • Istruzioni in Markdown

    Un file SKILL.md che il modello carica quando serve, consumando token solo quando una richiesta è effettivamente pertinente.

  • Funziona con qualsiasi LLM

    Le skill IA sono in semplice Markdown, non in codice specifico di un fornitore, quindi funzionano con GPT, Claude, Gemini, Grok o un modello locale.

  • Tutto nelle istruzioni

    Tutto ciò che serve al modello è nelle istruzioni: nessun file aggiuntivo da sincronizzare.

  • Open source

    Pubblicata da cosmicstack-labs su GitHub. Leggi i sorgenti prima di installarla.

Installazione

Installa la skill IA Python Patterns in TypingMind per usarla con qualsiasi LLM, oppure copiala in un altro agente in grado di leggere SKILL.md.

1

Installa in TypingMind

TypingMind installa una skill direttamente dalla sua cartella GitHub: legge SKILL.md, raccoglie i file delle risorse e salva il risultato in locale.

  1. Apri l'app e vai su Plugin → Skill.
  2. Scegli "Installa da GitHub".
  3. Incolla l'URL della cartella della skill riportato qui sotto e conferma.
    https://github.com/cosmicstack-labs/mercury-agent-skills/tree/main/categories/backend/python-patterns
  4. Attiva la skill in ogni chat in cui vuoi averla a disposizione.
Plugin → Skill → Aggiungi skill → Da URL GitHub, poi incolla l'URL della cartella e premi Continua.
2

Installa in un altro agente

Qualsiasi agente che legge il formato Agent Skills può usare questa skill: copia la cartella della skill nella directory delle skill di quell'agente.

Claude Code — .claude/skills
git clone --depth 1 https://github.com/cosmicstack-labs/mercury-agent-skills.git /tmp/mercury-agent-skills
mkdir -p .claude/skills
cp -r /tmp/mercury-agent-skills/categories/backend/python-patterns .claude/skills/python-patterns
Dopo la copia, riavvia Claude Code per caricare la nuova skill.

Usala in TypingMind

Attiva Python Patterns in qualsiasi chat di TypingMind e al resto pensa il modello. Il nome e la descrizione della skill sono nel prompt di sistema e, non appena arriva una richiesta pertinente, il modello carica da solo le istruzioni complete: non devi mai richiamarla manualmente e non consuma token finché non viene effettivamente usata.

Il modello carica automaticamente Python Patterns non appena riceve una richiesta pertinente.

Funziona con qualsiasi modello IA

Le skill IA sono semplici istruzioni in Markdown, non codice specifico di un fornitore, quindi Python Patterns non è vincolata al modello per cui è stata scritta. Installala una sola volta in TypingMind e usala con GPT-5, Claude, Gemini, Grok, DeepSeek, Mistral, Llama o un modello locale che esegui tu, sempre con le tue chiavi API.

  • Caricata solo quando serve

    Il prompt di sistema contiene solo il nome e la descrizione. Le istruzioni vengono recuperate alla prima richiesta pertinente, quindi una skill inutilizzata non costa nulla.

  • Cambia modello durante la chat

    Poiché la skill è composta da istruzioni e non da codice, continua a funzionare anche se cambi modello: il nuovo modello legge lo stesso file SKILL.md.

Istruzioni della skill

Questo è il contenuto di SKILL.md che il modello carica. Leggilo prima dell'installazione: una skill è un insieme di istruzioni che il tuo modello seguirà.

Python Patterns

Write Python that is type-safe, testable, and a joy to maintain.

Core Principles

1. Explicit Over Implicit

Use type hints. Avoid *args and **kwargs when named parameters work. Favor clear interfaces over dynamic flexibility.

2. Composition Over Inheritance

Python's multiple inheritance is powerful but dangerous. Prefer composition and protocols over deep class hierarchies.

3. Async Done Right

Async is a tool for I/O-bound workloads, not a universal default. Use synchronous code for CPU-bound tasks, async for network calls and file I/O.

4. Test-First for Critical Paths

Your business logic should be testable without mocks. Use dependency injection. Keep I/O at the boundaries.


Python Maturity Model

LevelTypingAsyncTestingStructure
1: ScriptNo type hintssync onlyManual testingSingle file
2: ModuleBasic types (str, int)Basic asynciopytest, some coveragePackage with __init__.py
3: PackageFull type hints with mypyAsync with proper patternspytest + fixtures + mockingsrc-layout, entry points
4: ServiceGenerics, Protocols, TypedDictStructured concurrencyProperty-based, integration testsDomain-driven structure
5: LibraryPrecise types, variance annotationsTrio / anyioFuzzing, benchmark testsPublic API surface explicit

Target: Level 3+ for production services.


Actionable Guidance

Type Hints

Basic Patterns
python
from typing import Optional, Union, Sequence, TypeVar, Protocol, Any
from datetime import datetime

# Function signatures
def process_user(
    user_id: int,
    name: str,
    email: Optional[str] = None,
    tags: list[str] | None = None,  # Python 3.10+ union syntax
) -> dict[str, Any]:
    ...

# TypedDict for structured dicts
class UserData(TypedDict, total=False):
    id: int
    name: str
    email: str
    created_at: datetime

# Protocols (structural subtyping)
class Drawable(Protocol):
    def draw(self, context: Any) -> None: ...

def render(item: Drawable) -> None:
    item.draw(...)  # Any object with draw() method works
Generic Types
python
T = TypeVar('T')
U = TypeVar('U', bound=Comparable)

class Repository(Generic[T]):
    def get(self, id: int) -> T | None: ...
    def list(self) -> Sequence[T]: ...
    def save(self, item: T) -> T: ...

Async Patterns

Proper Async Context Managers
python
import asyncio
from contextlib import asynccontextmanager

@asynccontextmanager
async def db_session():
    session = await create_session()
    try:
        yield session
    finally:
        await session.close()

# Usage
async with db_session() as session:
    result = await session.query(...)
Structured Concurrency
python
async def fetch_all_data():
    # Run tasks concurrently with proper error propagation
    async with asyncio.TaskGroup() as tg:
        task1 = tg.create_task(fetch_users())
        task2 = tg.create_task(fetch_orders())
        task3 = tg.create_task(fetch_products())

    # All tasks completed (or TaskGroup raised on error)
    return task1.result(), task2.result(), task3.result()
Timeouts and Cancellation
python
async def fetch_with_timeout(url: str, timeout: float = 10.0) -> Response:
    try:
        async with asyncio.timeout(timeout):
            return await fetch(url)
    except TimeoutError:
        logger.warning(f"Request to {url} timed out after {timeout}s")
        raise ServiceUnavailableError(f"Timeout fetching {url}")

Project Structure

Recommended: src layout

project/
├── pyproject.toml
├── src/
│   └── mypackage/
│       ├── __init__.py
│       ├── domain/       # Business logic
│       │   ├── models.py
│       │   └── services.py
│       ├── infrastructure/  # External dependencies
│       │   ├── database.py
│       │   └── http_client.py
│       ├── api/           # Entry points
│       │   └── routes.py
│       └── config.py
├── tests/
│   ├── unit/
│   ├── integration/
│   └── conftest.py
└── README.md

pyproject.toml (modern Python packaging):

toml
[build-system]
requires = ["setuptools>=68.0"]
build-backend = "setuptools.build_meta"

[project]
name = "mypackage"
version = "0.1.0"
dependencies = [
    "fastapi>=0.100",
    "pydantic>=2.0",
]

Testing Patterns

Fixtures for Clean Tests
python
import pytest
from datetime import datetime, timezone

@pytest.fixture
def sample_user() -> UserData:
    return UserData(
        id=1,
        name="Alice",
        email="alice@example.com",
        created_at=datetime.now(timezone.utc),
    )

@pytest.fixture
def repo(in_memory_db):
    return UserRepository(in_memory_db)

def test_create_user(repo, sample_user):
    saved = repo.save(sample_user)
    assert saved.id == 1
    assert saved.name == "Alice"

def test_get_nonexistent_user(repo):
    result = repo.get(999)
    assert result is None
Testing Async Code
python
@pytest.mark.asyncio
async def test_async_service():
    service = UserService(client=MockAsyncClient())
    result = await service.get_user(42)
    assert result.name == "Alice"
Property-Based Testing
python
from hypothesis import given, strategies as st

@given(st.integers(min_value=1, max_value=1000))
def test_user_id_is_positive(user_id: int):
    result = process_user(user_id)
    assert result["user_id"] > 0

@given(st.emails())
def test_valid_email_format(email: str):
    assert validate_email(email) is True

Error Handling

Custom Exception Hierarchy
python
class AppError(Exception):
    """Base exception for application errors."""
    def __init__(self, message: str, code: str | None = None):
        super().__init__(message)
        self.code = code or "UNKNOWN_ERROR"

class NotFoundError(AppError):
    def __init__(self, resource: str, id: int | str):
        super().__init__(f"{resource} not found: {id}", code="NOT_FOUND")

class ValidationError(AppError):
    def __init__(self, message: str, field: str | None = None):
        super().__init__(message, code="VALIDATION_ERROR")
        self.field = field
Result Pattern (Alternative to Exceptions)
python
from dataclasses import dataclass
from typing import Generic, TypeVar

T = TypeVar('T')
E = TypeVar('E')

@dataclass
class Ok(Generic[T]):
    value: T

@dataclass
class Err(Generic[E]):
    error: E

Result = Ok[T] | Err[E]

def get_user(user_id: int) -> Result[User, AppError]:
    user = database.find(user_id)
    if user is None:
        return Err(NotFoundError("User", user_id))
    return Ok(user)

Common Mistakes

  1. Mutable default arguments: def func(items=[]) — creates one list shared across calls. Use None and initialize inside.
  2. Ignoring type hints in hot paths: Type hints have minimal runtime cost but catch bugs early. Use mypy/pyright in CI.
  3. Blocking the event loop: Calling requests.get() inside async code blocks all coroutines. Use httpx.AsyncClient.
  4. Overusing **kwargs: Pass-through kwargs obscure function signatures. Be explicit about parameters.
  5. Not using __slots__: For classes with many instances, __slots__ reduces memory by ~50%.
  6. Mixing sync and async carelessly: Calling async from sync (or vice versa) requires careful handling. Use asyncio.run() only at entry points.
  7. Deep nested context managers: Chain too many async with blocks. Extract into helper methods or context manager composition.

Domande frequenti

Cosa fa la skill IA Python Patterns?

Python best practices including type hints, async patterns, testing, and project structure

Perché usare Python Patterns su TypingMind?

Perché la installi una volta e la usi con qualsiasi modello. Python Patterns è scritta in semplice Markdown anziché in codice specifico di un fornitore, quindi la stessa skill funziona con GPT-5, Claude, Gemini, Grok o un modello locale, e puoi cambiare modello durante la chat senza che la skill smetta di funzionare. TypingMind usa le tue chiavi API, quindi paghi direttamente i fornitori anziché un abbonamento per posto utente, e le tue skill e chat restano nel tuo spazio di archiviazione.

Come installo Python Patterns in TypingMind?

Apri Plugin → Skill → Installa da GitHub in TypingMind e incolla https://github.com/cosmicstack-labs/mercury-agent-skills/tree/main/categories/backend/python-patterns. TypingMind legge il file SKILL.md e installa la skill, che puoi abilitare per ogni singola chat.

Quali modelli IA possono usare Python Patterns?

Qualsiasi modello che colleghi a TypingMind. Le skill IA sono semplici istruzioni in Markdown anziché codice specifico di un fornitore, quindi GPT, Claude, Gemini, Grok e i modelli locali possono tutti caricare questa skill quando una richiesta corrisponde al suo scopo.

Quanti modelli IA posso usare con Python Patterns?

Quanti ne vuoi. Se un modello supporta le skill, puoi usarlo con Python Patterns: GPT, Claude, Gemini, Grok, DeepSeek, Mistral, Llama e molti altri, tutti su TypingMind con le tue chiavi API.

La skill IA Python Patterns è gratuita?

Sì. È pubblicata su GitHub da cosmicstack-labs con licenza MIT. Paghi solo il tuo fornitore IA per i token che usi.

Cosa sono le skill IA?

Una skill IA è un pacchetto di istruzioni riutilizzabili che insegna a un modello IA come svolgere un'attività specifica. Segue il formato aperto Agent Skills: un file SKILL.md con un nome e una descrizione, più eventuali script, template o file di riferimento di cui il modello potrebbe aver bisogno. Il modello legge le istruzioni solo quando la tua richiesta corrisponde alla skill, quindi una skill installata non comporta costi finché non viene usata.

In cosa si differenziano le skill IA dai plugin o dai server MCP?

Un plugin o un server MCP fornisce a un modello nuovi strumenti da richiamare: codice che viene eseguito da qualche parte e restituisce un risultato. Una skill IA, invece, fornisce al modello conoscenze e procedure: come affrontare un'attività, quali passaggi seguire e quali caratteristiche deve avere un buon output. Le skill sono semplici istruzioni in Markdown, quindi non richiedono server, chiavi API né ambienti di esecuzione e funzionano con qualsiasi modello.

Elenco completo

Crea subito il tuo spazio di lavoro AI

Iscriviti alla nostra newsletter per ricevere aggiornamenti sulle nuove funzionalità e sulle prossime iniziative a premi 👇