Logo: Python Patterns

Python Patterns

Organisatioun
cosmicstack-labs
python-patterns

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

Iwwersiicht

Editeurcosmicstack-labs
Repositorymercury-agent-skills
Skill-Nummpython-patterns
Stären
485
Forks
63
Matgeliwwert Dateien
Nëmmen Instruktiounen
LizenzMIT
Linken
  • Instruktiounen am Markdown-Format

    Eng SKILL.md-Datei, déi de Modell bei Bedarf luet, soudatt nëmmen Token ufalen, wann eng Ufro tatsächlech dozou passt.

  • Funktionéiert mat all LLM

    KI-Skills si reng Markdown, keen ubidderspezifesche Code. Dofir funktionéiert dëse Skill mat GPT, Claude, Gemini, Grok oder engem lokale Modell.

  • Alles an den Instruktiounen

    Alles, wat de Modell brauch, steet an den Instruktiounen — keng zousätzlech Dateien ze synchroniséieren.

  • Open Source

    cosmicstack-labs huet de Skill op GitHub verëffentlecht. Liest de Quelltext, ier Dir de Skill installéiert.

Installatioun

Installéiert de KI-Skill Python Patterns an TypingMind, fir e mat all LLM ze benotzen, oder setzt en an en anere KI-Agent an, deen SKILL.md liest.

1

An TypingMind installéieren

TypingMind installéiert e Skill direkt aus sengem GitHub-Dossier — dobäi gëtt SKILL.md gelies, d'Ressourcedateie gi gebëndelt an d'Resultat gëtt lokal gespäichert.

  1. Maacht d'App op a gitt op Plugins → Skills.
  2. Wielt „Vu GitHub installéieren“.
  3. Pecht d'URL vum Skill-Dossier, déi hei drënner steet, an a bestätegt d'Installatioun.
    https://github.com/cosmicstack-labs/mercury-agent-skills/tree/main/categories/backend/python-patterns
  4. Aktivéiert de Skill an all Chat, an deem Dir e benotze wëllt.
Plugins → Skills → Skill derbäisetzen → Iwwer eng GitHub-URL. Pecht dann d'URL vum Dossier an a klickt op Weider.
2

An engem anere KI-Agent installéieren

All KI-Agent, deen d'Format Agent Skills liest, kann dëse Skill benotzen — kopéiert den Dossier an d'Skill-Verzeechnes vun deem KI-Agent.

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
Start Claude Code nom Kopéieren nei, fir datt den neie Skill erkannt gëtt.

An TypingMind benotzen

Aktivéiert Python Patterns an engem Chat vun TypingMind, an de Modell iwwerhëlt de Rescht. Den Numm an d'Beschreiwung stinn am System-Prompt. Soubal eng Ufro dozou passt, luet de Modell déi komplett Instruktioune selwer — Dir musst de Skill ni manuell opruffen, an et fale keng Token un, bis en tatsächlech benotzt gëtt.

De Modell luet Python Patterns automatesch, soubal eng Ufro dozou passt.

Funktionéiert mat all KI-Modell

KI-Skills si reng Markdown-Instruktiounen amplaz vun ubidderspezifeschem Code. Dofir ass Python Patterns net un de Modell gebonnen, fir deen de Skill geschriwwe gouf. Installéiert en eemol an TypingMind a benotzt e mat GPT-5, Claude, Gemini, Grok, DeepSeek, Mistral, Llama oder engem lokale Modell, deen Dir selwer bedreift — alles mat Ären eegenen API-Schlësselen.

  • Gëtt nëmme gelueden, wann et néideg ass

    De System-Prompt enthält nëmmen den Numm an d'Beschreiwung. D'Instruktioune gi bei der éischter passender Ufro gelueden, soudatt en onbenotzte Skill näischt kascht.

  • De Modell am lafende Chat wiesselen

    Well de Skill aus Instruktiounen amplaz vu Code besteet, funktionéiert en och no engem Modellwiessel — den nächste Modell liest déi selwecht SKILL.md-Datei.

Skill-Instruktiounen

Dëst ass den Inhalt vu SKILL.md, deen de Modell luet. Liest e virun der Installatioun — e Skill besteet aus Instruktiounen, déi Äre Modell befollegt.

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.

Heefeg gestallte Froen

Wat mécht de KI-Skill Python Patterns?

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

Firwat Python Patterns op TypingMind benotzen?

Well Dir en eemol installéiert a mat all Modell benotze kënnt. Python Patterns besteet aus einfachem Markdown amplaz vun ubidderspezifeschem Code. Dee selwechte Skill funktionéiert also mat GPT-5, Claude, Gemini, Grok oder engem lokale Modell – an Dir kënnt de Modell matzen am Chat wiesselen, ouni datt de Skill ophält ze funktionéieren. TypingMind benotzt Är eegen API-Schlësselen, sou datt Dir d'Ubidder direkt bezuelt, amplaz en Abonnement pro Benotzerplaz ze bezuelen. Är Skills a Chats bleiwen an Ärem eegene Späicher.

Wéi installéieren ech Python Patterns an TypingMind?

Maacht an TypingMind Plugins → Skills → Vu GitHub installéieren op a setzt https://github.com/cosmicstack-labs/mercury-agent-skills/tree/main/categories/backend/python-patterns an. TypingMind liest d'Datei SKILL.md an installéiert de Skill, deen Dir pro Chat aktivéiere kënnt.

Wéi eng KI-Modeller kënnen Python Patterns benotzen?

All Modell, deen Dir an TypingMind verbënnt. KI-Skills sinn einfach Markdown-Instruktiounen an net ubidderspezifesche Code. Dofir kënne GPT, Claude, Gemini, Grok a lokal Modeller dëse Skill lueden, wann eng Ufro dozou passt.

Wéi vill KI-Modeller kann ech mat Python Patterns benotzen?

Esou vill wéi Dir wëllt. Soulaang e Modell Skills ënnerstëtzt, kënnt Dir Python Patterns domat benotzen – zum Beispill mat GPT, Claude, Gemini, Grok, DeepSeek, Mistral oder Llama – alles op TypingMind mat Ären eegenen API-Schlësselen.

Ass de KI-Skill Python Patterns gratis?

Jo. cosmicstack-labs huet de Skill ënner der Lizenz MIT op GitHub publizéiert. Dir bezuelt nëmmen Ären eegene KI-Ubidder fir d'Token, déi Dir benotzt.

Wat si KI-Skills?

E KI-Skill ass e weiderverwendbare Pak vun Instruktiounen, deen engem KI-Modell bäibréngt, wéi en eng bestëmmt Aufgab erfëllt. E follegt dem oppenen Agent Skills-Format: eng Datei SKILL.md mat engem Numm an enger Beschreiwung, plus all Scripten, Virlagen oder Referenzdateien, déi de Modell eventuell brauch. De Modell liest d'Instruktiounen eréischt, wann Är Ufro zum Skill passt. En installéierte Skill kascht also näischt, bis e benotzt gëtt.

Wéi ënnerscheede sech KI-Skills vu Plugins oder MCP-Serveren?

E Plugin oder MCP-Server gëtt engem Modell nei Tools, déi en opruffe kann – Code, deen iergendwou leeft an e Resultat zeréckgëtt. E KI-Skill gëtt dem Modell dogéint Wëssen an eng Virgoensweis: wéi en eng Aufgab ugeet, wéi eng Schrëtt e maache soll a wéi eng gutt Ausgab ausgesäit. Skills bestinn aus einfachem Markdown, brauche kee Server, keen API-Schlëssel a kee Lafzäitëmfeld a funktionéiere mat all Modell.

Alleguer weisen

Elo Ären eegene KI-Aarbechtsberäich ariichten

Abonnéiert Iech op eisen Newsletter, fir iwwer nei Funktiounen an zukünfteg Gewënnspiller informéiert ze ginn 👇