New advertisers: 50% off your first month with code FIRSTMONTHSee slots

Python 3.13+ expertise plugin covering async, type hints, FastAPI, testing, and cloud deployment.

version
2.3.6
GitHub stars
62
View on GitHub

What it does

  • Adds /python-init and /python-test commands plus a python-expert agent for Python 3.13+ work
  • Covers 12 skills spanning asyncio, type hints, package management, FastAPI, pytest, and Cloudflare Workers
  • Includes OpenCV and FFmpeg guides that flag gotchas such as BGR color order and dropped audio streams
  • Designed for developers building Python services, video pipelines, or CI workflows with uv and GitHub Actions

Comprehensive Python 3.13+ expertise covering modern Python, async, types, performance, and cloud deployment. PROACTIVELY activate for: (1) any Python task, (2) 3.13+ features (free-threading, JIT), (3) asyncio and concurrency, (4) type hints with mypy/pyright, (5) package management (uv/pip/poetry), (6) project layout, (7) FastAPI, (8) Pydantic, (9) pytest, (10) Cloudflare Workers/Containers Python, (11) GitHub Actions workflows, (12) profiling, (13) OWASP security, (14) Ruff linting. Provides: production patterns, memory profiling, dataclass vs Pydantic guidance.

Add marketplace

/plugin marketplace add JosiahSiegel/claude-plugin-marketplace

Run it inside Claude Code once, then install the plugin below.

Install

/plugin install python-master@claude-plugin-marketplace

Run it inside Claude Code after adding the marketplace.

Files

Discovered from source

Quick Reference

FunctionPurposeCode
asyncio.run()Entry pointasyncio.run(main())
asyncio.gather()Concurrent tasksawait asyncio.gather(*tasks)
asyncio.create_task()Fire-and-awaittask = asyncio.create_task(coro)
asyncio.TaskGroup()Structured concurrencyasync with asyncio.TaskGroup() as tg:
asyncio.Semaphore()Rate limitingasync with semaphore:
asyncio.timeout()Timeout (3.11+)async with asyncio.timeout(5.0):
PatternSequentialConcurrent
Executionawait a(); await b()await gather(a(), b())
TimeSum of durationsMax of durations
LibraryUse Case
aiohttpHTTP client (most popular)
httpxHTTP (sync + async)
asyncpgPostgreSQL
uvloop2-4x faster event loop

When to Use This Skill

Use for async/concurrent programming:

  • Network requests (HTTP, WebSockets)
  • Database queries
  • File I/O operations
  • Multiple concurrent I/O operations
  • FastAPI/Starlette async endpoints

Related skills:

  • For FastAPI: see python-fastapi
  • For type hints: see python-type-hints
  • For gotchas: see python-gotchas

Python Asyncio Complete Guide

Overview

Asyncio is Python's built-in framework for writing concurrent code using async/await syntax. It's ideal for I/O-bound operations like network requests, file I/O, and database queries.

When to Use Asyncio

Good Use Cases

  • Network requests (HTTP clients, WebSockets)
  • Database queries
  • File I/O operations
  • Web servers (FastAPI, Starlette)
  • Message queues
  • Multiple concurrent I/O operations

When NOT to Use

  • CPU-bound tasks (use multiprocessing instead)
  • Simple sequential scripts
  • Legacy codebases without async support

Core Concepts

Basic Async/Await

import asyncio

# Async function (coroutine)
async def fetch_data(url: str) -> dict:
    # Simulated async I/O
    await asyncio.sleep(1)
    return {"url": url, "data": "..."}

# Running a coroutine
async def main():
    result = await fetch_data("https://api.example.com")
    print(result)

# Entry point
asyncio.run(main())

Concurrent Execution with gather()

import asyncio
import aiohttp

async def fetch_url(session: aiohttp.ClientSession, url: str) -> dict:
    async with session.get(url) as response:
        return {"url": url, "status": response.status}

async def fetch_all(urls: list[str]) -> list[dict]:
    async with aiohttp.ClientSession() as session:
        # Run all requests concurrently
        tasks = [fetch_url(session, url) for url in urls]
        results = await asyncio.gather(*tasks)
        return results

# Usage
urls = [
    "https://api.example.com/1",
    "https://api.example.com/2",
    "https://api.example.com/3",
]
results = asyncio.run(fetch_all(urls))

TaskGroup (Python 3.11+)

import asyncio

async def process_item(item: str) -> str:
    await asyncio.sleep(1)
    return f"Processed: {item}"

async def process_all(items: list[str]) -> list[str]:
    results = []

    # TaskGroup provides structured concurrency
    async with asyncio.TaskGroup() as tg:
        tasks = [tg.create_task(process_item(item)) for item in items]

    # All tasks complete when exiting the context
    return [task.result() for task in tasks]

# Exception handling with TaskGroup
async def process_with_errors(items: list[str]):
    try:
        async with asyncio.TaskGroup() as tg:
            for item in items:
                tg.create_task(process_item(item))
    except* ValueError as eg:
        # Handle ValueError exceptions
        for exc in eg.exceptions:
            print(f"ValueError: {exc}")
    except* TypeError as eg:
        # Handle TypeError exceptions
        for exc in eg.exceptions:
            print(f"TypeError: {exc}")

create_task() vs await

import asyncio

async def task_a():
    await asyncio.sleep(2)
    return "A done"

async def task_b():
    await asyncio.sleep(1)
    return "B done"

# Sequential (slower - 3 seconds total)
async def sequential():
    result_a = await task_a()  # Wait 2 seconds
    result_b = await task_b()  # Wait 1 second
    return result_a, result_b

# Concurrent (faster - 2 seconds total)
async def concurrent():
    task1 = asyncio.create_task(task_a())  # Start immediately
    task2 = asyncio.create_task(task_b())  # Start immediately
    result_a = await task1
    result_b = await task2
    return result_a, result_b

# Using gather (recommended for multiple tasks)
async def concurrent_gather():
    result_a, result_b = await asyncio.gather(task_a(), task_b())
    return result_a, result_b

Advanced Patterns

Semaphores for Rate Limiting

import asyncio
import aiohttp

async def fetch_with_limit(
    session: aiohttp.ClientSession,
    url: str,
    semaphore: asyncio.Semaphore
) -> dict:
    async with semaphore:  # Limits concurrent requests
        async with session.get(url) as response:
            return await response.json()

async def fetch_many(urls: list[str], max_concurrent: int = 10) -> list[dict]:
    semaphore = asyncio.Semaphore(max_concurrent)

    async with aiohttp.ClientSession() as session:
        tasks = [fetch_with_limit(session, url, semaphore) for url in urls]
        return await asyncio.gather(*tasks)

Timeouts

import asyncio

async def slow_operation():
    await asyncio.sleep(10)
    return "done"

async def with_timeout():
    try:
        # Wait at most 5 seconds
        result = await asyncio.wait_for(slow_operation(), timeout=5.0)
        return result
    except asyncio.TimeoutError:
        print("Operation timed out")
        return None

# Using timeout context manager (Python 3.11+)
async def with_timeout_context():
    async with asyncio.timeout(5.0):
        result = await slow_operation()
        return result

Queues for Producer-Consumer

import asyncio
from typing import Any

async def producer(queue: asyncio.Queue, items: list[Any]):
    for item in items:
        await queue.put(item)
        print(f"Produced: {item}")
    # Signal completion
    await queue.put(None)

async def consumer(queue: asyncio.Queue, consumer_id: int):
    while True:
        item = await queue.get()
        if item is None:
            # Put sentinel back for other consumers
            await queue.put(None)
            break
        print(f"Consumer {consumer_id} processing: {item}")
        await asyncio.sleep(0.5)  # Simulate work
        queue.task_done()

async def main():
    queue: asyncio.Queue = asyncio.Queue(maxsize=10)

    items = list(range(20))

    # Start producer and consumers
    async with asyncio.TaskGroup() as tg:
        tg.create_task(producer(queue, items))
        for i in range(3):
            tg.create_task(consumer(queue, i))

asyncio.run(main())

Async Generators

import asyncio
from typing import AsyncIterator

async def fetch_pages(url: str, max_pages: int = 10) -> AsyncIterator[dict]:
    """Async generator for paginated API."""
    page = 1
    while page <= max_pages:
        # Simulate API call
        await asyncio.sleep(0.1)
        data = {"page": page, "items": [f"item_{i}" for i in range(10)]}

        if not data["items"]:
            break

        yield data
        page += 1

async def process_pages():
    async for page_data in fetch_pages("https://api.example.com"):
        print(f"Processing page {page_data['page']}")
        for item in page_data["items"]:
            process(item)

Async Context Managers

from contextlib import asynccontextmanager
from typing import AsyncIterator

class AsyncDatabaseConnection:
    async def __aenter__(self):
        await self.connect()
        return self

    async def __aexit__(self, exc_type, exc_val, exc_tb):
        await self.disconnect()
        return False

    async def connect(self):
        print("Connecting...")
        await asyncio.sleep(0.1)

    async def disconnect(self):
        print("Disconnecting...")
        await asyncio.sleep(0.1)

# Using decorator
@asynccontextmanager
async def async_session() -> AsyncIterator[dict]:
    session = {"connected": True}
    try:
        yield session
    finally:
        session["connected"] = False
        await asyncio.sleep(0.1)  # Cleanup

# Usage
async def main():
    async with AsyncDatabaseConnection() as db:
        await db.query("SELECT * FROM users")

    async with async_session() as session:
        print(session)

Performance Optimization

Eager Task Factory (Python 3.12+)

import asyncio

async def cached_operation(key: str) -> str:
    cache = {"a": "value_a", "b": "value_b"}
    if key in cache:
        return cache[key]  # Returns synchronously
    await asyncio.sleep(1)  # Only if cache miss
    return f"fetched_{key}"

async def main():
    loop = asyncio.get_event_loop()
    # Enable eager task execution
    loop.set_task_factory(asyncio.eager_task_factory)

    # Cached operations complete synchronously without event loop overhead
    result = await cached_operation("a")

Using uvloop

# Install: pip install uvloop

import asyncio

try:
    import uvloop
    # 2-4x performance improvement
    asyncio.set_event_loop_policy(uvloop.EventLoopPolicy())
except ImportError:
    pass  # Fall back to default event loop

async def main():
    # Your async code here
    pass

asyncio.run(main())

Free-Threaded asyncio (Python 3.14+)

# Python 3.14 improvements for free-threaded builds:
# - Thread-safe asyncio with lock-free data structures
# - Linear scaling with number of threads
# - 10-20% single-threaded performance improvement
# - Reduced memory usage

import asyncio
import threading

async def per_thread_loop():
    """Each thread can run its own event loop."""
    loop = asyncio.new_event_loop()
    asyncio.set_event_loop(loop)
    try:
        await asyncio.sleep(1)
    finally:
        loop.close()

# Multiple event loops in parallel (free-threaded build)
threads = [
    threading.Thread(target=lambda: asyncio.run(per_thread_loop()))
    for _ in range(4)
]
for t in threads:
    t.start()
for t in threads:
    t.join()

Common Gotchas

Blocking the Event Loop

import asyncio
import time

# BAD: Blocks the event loop
async def bad_example():
    time.sleep(5)  # Blocks everything!
    return "done"

# GOOD: Use async sleep
async def good_example():
    await asyncio.sleep(5)
    return "done"

# GOOD: Run blocking code in executor
async def blocking_in_executor():
    loop = asyncio.get_event_loop()
    result = await loop.run_in_executor(None, time.sleep, 5)
    return result

# For CPU-bound work, use ProcessPoolExecutor
from concurrent.futures import ProcessPoolExecutor

async def cpu_bound_work(data: list) -> list:
    loop = asyncio.get_event_loop()
    with ProcessPoolExecutor() as pool:
        result = await loop.run_in_executor(pool, heavy_computation, data)
    return result

Creating Tasks in Wrong Context

import asyncio

# BAD: Task created outside async context
# task = asyncio.create_task(some_coroutine())  # RuntimeError!

# GOOD: Create tasks inside async function
async def main():
    task = asyncio.create_task(some_coroutine())
    await task

asyncio.run(main())

Forgetting to Await

import asyncio

async def fetch():
    await asyncio.sleep(1)
    return "data"

# BAD: Coroutine never executed
async def bad():
    result = fetch()  # Just creates coroutine object!
    print(result)     # Prints coroutine object, not "data"

# GOOD: Always await coroutines
async def good():
    result = await fetch()
    print(result)  # Prints "data"

Exception Handling in Tasks

import asyncio

async def failing_task():
    await asyncio.sleep(1)
    raise ValueError("Task failed!")

async def main():
    # BAD: Exception silently lost
    task = asyncio.create_task(failing_task())
    await asyncio.sleep(2)  # Task exception ignored

    # GOOD: Always await tasks or use TaskGroup
    task = asyncio.create_task(failing_task())
    try:
        await task
    except ValueError as e:
        print(f"Caught: {e}")

    # BEST: Use TaskGroup (Python 3.11+)
    try:
        async with asyncio.TaskGroup() as tg:
            tg.create_task(failing_task())
    except* ValueError as eg:
        for exc in eg.exceptions:
            print(f"Caught: {exc}")

Async Libraries

HTTP Clients

# aiohttp - Most popular
import aiohttp

async def fetch_aiohttp(url: str) -> dict:
    async with aiohttp.ClientSession() as session:
        async with session.get(url) as response:
            return await response.json()

# httpx - Supports both sync and async
import httpx

async def fetch_httpx(url: str) -> dict:
    async with httpx.AsyncClient() as client:
        response = await client.get(url)
        return response.json()

Database

# asyncpg - PostgreSQL
import asyncpg

async def query_postgres():
    conn = await asyncpg.connect("postgresql://user:pass@localhost/db")
    rows = await conn.fetch("SELECT * FROM users")
    await conn.close()
    return rows

# aiosqlite - SQLite
import aiosqlite

async def query_sqlite():
    async with aiosqlite.connect("database.db") as db:
        async with db.execute("SELECT * FROM users") as cursor:
            return await cursor.fetchall()

Web Frameworks

# FastAPI (built on Starlette)
from fastapi import FastAPI

app = FastAPI()

@app.get("/items/{item_id}")
async def read_item(item_id: int):
    return {"item_id": item_id}

# Starlette
from starlette.applications import Starlette
from starlette.responses import JSONResponse
from starlette.routing import Route

async def homepage(request):
    return JSONResponse({"hello": "world"})

app = Starlette(routes=[Route("/", homepage)])

Additional References

For production-ready patterns beyond this guide, see:

  • Async Patterns Library - Token bucket rate limiter, retry with exponential backoff, connection pools, batch processors, event bus, transaction context managers, async cache with TTL, graceful shutdown handlers

Readme

Python Master Plugin

Comprehensive Python expertise for Claude Code, covering modern Python 3.13+ development, async programming, type hints, FastAPI, testing, Cloudflare deployment, and GitHub Actions optimization.

Features

This plugin provides expertise in:

  • Python 3.13+ Features - Free-threading, JIT, pattern matching, type parameters
  • Asyncio Mastery - TaskGroup, semaphores, uvloop, async patterns
  • Type Hints - Protocols, TypedDict, generics, mypy/pyright
  • Package Management - uv, pyproject.toml, src layout, Ruff
  • FastAPI - Production patterns, Pydantic, async handlers
  • Testing - pytest, fixtures, mocking, coverage, async tests
  • Cloudflare - Python Workers, Containers, cold start optimization
  • GitHub Actions - uv CI/CD, caching, matrix builds, PyPI publishing
  • Security - OWASP compliance, input validation, secrets management
  • Performance - Memory profiling, optimization techniques
  • OpenCV - Computer vision, image/video processing, BGR gotchas, DNN inference
  • FFmpeg - Video/audio processing, encoding, streaming, ffmpeg-python, PyAV
  • Video Pipelines - FFmpeg + OpenCV + Modal.com integration, parallel processing, GPU acceleration

Skills

SkillDescription
python-fundamentals-313Python 3.13+ features, syntax, memory optimizations
python-asyncioAsync/await patterns, TaskGroup, performance
python-type-hintsModern type hints, Protocols, generics
python-package-managementuv, pyproject.toml, Ruff, project structure
python-fastapiFastAPI production patterns, Pydantic, deployment
python-testingpytest, fixtures, mocking, coverage
python-cloudflareWorkers, Containers, optimization
python-github-actionsCI/CD workflows, caching, publishing
python-gotchasCommon pitfalls and how to avoid them
python-opencvComputer vision, image/video processing, BGR handling
python-ffmpegVideo/audio encoding, streaming, ffmpeg-python, PyAV
python-video-pipelineFFmpeg + OpenCV + Modal integration, parallel GPU processing

Commands

CommandDescription
/python-initInitialize a new Python project with best practices
/python-testRun tests with coverage report

Quick Reference

Modern Python (3.12+)

# Type parameters
def first[T](items: list[T]) -> T:
    return items[0]

# Pattern matching
match command:
    case {"action": "create", "name": str(name)}:
        return create(name)
    case _:
        return error()

# Type alias
type JsonValue = str | int | float | bool | None | list["JsonValue"]

Async Patterns

import asyncio

async def fetch_all(urls: list[str]) -> list[dict]:
    async with asyncio.TaskGroup() as tg:
        tasks = [tg.create_task(fetch(url)) for url in urls]
    return [task.result() for task in tasks]

FastAPI

from fastapi import FastAPI, Depends
from pydantic import BaseModel

app = FastAPI()

class Item(BaseModel):
    name: str
    price: float

@app.post("/items/")
async def create_item(item: Item):
    return item

uv Package Management

# Create project
uv init my-project

# Add dependencies
uv add fastapi pydantic

# Run with virtual env
uv run python main.py

# Sync from lockfile
uv sync

pytest Testing

import pytest

@pytest.fixture
def sample_data():
    return {"key": "value"}

@pytest.mark.asyncio
async def test_async_function(sample_data):
    result = await process(sample_data)
    assert result is not None

Cloudflare Workers

from workers import Response, WorkerEntrypoint

class Default(WorkerEntrypoint):
    async def fetch(self, request):
        return Response("Hello from Python Worker!")

GitHub Actions

- uses: astral-sh/setup-uv@v4
  with:
    enable-cache: true
- run: uv sync
- run: uv run pytest

OpenCV

import cv2
import numpy as np

# CRITICAL: OpenCV uses BGR, not RGB!
img = cv2.imread("image.jpg")  # BGR format

# Convert to RGB for Matplotlib/PIL
rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)

# Coordinate gotcha: img[y, x] not img[x, y]
pixel = img[100, 200]  # row=100 (y), col=200 (x)

# Always check if image loaded
if img is None:
    raise FileNotFoundError("Image not found")

# Video capture with proper cleanup
cap = cv2.VideoCapture(0)
try:
    while cap.isOpened():
        ret, frame = cap.read()
        if not ret:
            break
        # Process frame...
finally:
    cap.release()
    cv2.destroyAllWindows()

FFmpeg

import ffmpeg

# CRITICAL: Video filters can drop audio!
# BAD: Audio is lost
ffmpeg.input('input.mp4').filter('scale', 1280, 720).output('out.mp4').run()

# GOOD: Explicitly handle both streams
input_file = ffmpeg.input('input.mp4')
video = input_file.video.filter('scale', 1280, 720)
audio = input_file.audio
ffmpeg.output(video, audio, 'output.mp4').overwrite_output().run()

# Get video info
probe = ffmpeg.probe('video.mp4')
duration = float(probe['format']['duration'])

# H.264 encoding with quality control
ffmpeg.input('input.mp4').output('output.mp4',
    vcodec='libx264',
    crf=23,           # 0=lossless, 23=default, 51=worst
    preset='medium',  # ultrafast to veryslow
    acodec='aac',
    audio_bitrate='192k'
).overwrite_output().run()

# Extract audio
ffmpeg.input('video.mp4').output('audio.mp3',
    acodec='libmp3lame',
    audio_bitrate='320k',
    vn=None  # No video
).overwrite_output().run()

# Always use overwrite_output() to avoid prompts
# Always handle errors with try/except ffmpeg.Error

Video Pipeline (FFmpeg + OpenCV + Modal)

import modal

# Modal image with FFmpeg and OpenCV
image = (
    modal.Image.debian_slim()
    .apt_install("ffmpeg", "libsm6", "libxext6", "libgl1")
    .pip_install("opencv-python-headless", "ffmpeg-python", "numpy")
)

app = modal.App("video-pipeline", image=image)

@app.function(gpu="T4")
def process_video(video_bytes: bytes) -> bytes:
    """Process video with GPU acceleration."""
    import cv2
    import numpy as np
    import tempfile

    # Write input to temp file
    with tempfile.NamedTemporaryFile(suffix='.mp4') as f:
        f.write(video_bytes)
        cap = cv2.VideoCapture(f.name)

    # Process frames...
    # CRITICAL: Color format - OpenCV=BGR, FFmpeg=RGB by default
    # CRITICAL: Frame shape - img[y, x] not img[x, y]

    return processed_bytes

# Parallel frame processing
@app.function()
def process_frame(frame_data: bytes) -> bytes:
    import cv2
    import numpy as np
    nparr = np.frombuffer(frame_data, np.uint8)
    frame = cv2.imdecode(nparr, cv2.IMREAD_COLOR)
    processed = cv2.GaussianBlur(frame, (5, 5), 0)
    _, encoded = cv2.imencode('.png', processed)
    return encoded.tobytes()

# Use .map() for parallel processing
results = list(process_frame.map(frame_list))

Best Practices Covered

Code Quality

  • Type annotations for all public APIs
  • Ruff for consistent formatting/linting
  • Mypy strict mode for type safety

Project Structure

  • src layout for packages
  • pyproject.toml for all configuration
  • uv for fast, reproducible environments

Testing

  • pytest with fixtures
  • 80%+ code coverage
  • Async test support

Performance

  • Async for I/O-bound operations
  • Memory profiling with memray/tracemalloc
  • Efficient data structures

Security

  • Input validation with Pydantic
  • Parameterized queries
  • Dependency auditing with pip-audit

Installation

Via GitHub Marketplace (Recommended)

/plugin marketplace add claude-plugin-marketplace
/plugin install python-master@claude-plugin-marketplace

Local Installation (Mac/Linux)

unzip python-master.zip -d ~/.local/share/claude/plugins/

License

MIT

Links

Details

Marketplace
JosiahSiegel/claude-plugin-marketplace
Source
plugins/python-master
Author
Josiah Siegel
Category
Community
Keywords
python, python3.13, asyncio, type-hints, mypy, uv, fastapi, pydantic, pytest, cloudflare-workers, cloudflare-containers, github-actions, performance, ruff, security, dataclass, typing, async, free-threading, jit, modal, modal-com, serverless, gpu, ml-inference, scheduled-tasks, parallel-processing, opencv, cv2, computer-vision, image-processing, video-processing, contours, edge-detection, feature-detection, dnn, deep-learning-inference, ffmpeg, ffmpeg-python, pyav, video-encoding, audio-processing, h264, h265, hevc, vp9, av1, transcoding, hls, dash, rtmp, streaming, crf, nvenc, hardware-acceleration, thumbnail, gif, ffprobe, video-filters, audio-extraction, video-pipeline, ffmpegcv, vidgear, decord, camgear, writegear, video-reader, video-writer, frame-processing, parallel-video, chunk-processing, modal-video, gpu-video, nvdec, cuda-video, batch-frames, video-streaming, rtsp, video-api, video-upload, video-transcode, quality-ladder, adaptive-streaming
Listed since
Apr 7, 2026

More from JosiahSiegel/claude-plugin-marketplace

All 43

Similar to python-master

More Backend & APIs