Claude Code for uvloop: Fast asyncio Event Loop for Python — Claude Skills 360 Blog
Blog / AI / Claude Code for uvloop: Fast asyncio Event Loop for Python
AI

Claude Code for uvloop: Fast asyncio Event Loop for Python

Published: May 16, 2028
Read time: 5 min read
By: Claude Skills 360

uvloop is a fast drop-in asyncio event loop built on libuv. pip install uvloop. Install globally: import uvloop; uvloop.install() — call before any asyncio code. Or: asyncio.set_event_loop_policy(uvloop.EventLoopPolicy()). Or per-run: uvloop.run(main()). Check active loop: type(asyncio.get_event_loop())<class 'uvloop.Loop'>. Gunicorn: --worker-class uvloop.UVLoopWorker (or aiohttp.GunicornUVLoopWebWorker). aiohttp: web.run_app(app, loop=uvloop.new_event_loop()). FastAPI+uvicorn: uvicorn uses uvloop by default when installed (--loop uvloop flag). asyncio streams: fully compatible — asyncio.open_connection, asyncio.start_server. Subprocess: asyncio.create_subprocess_exec. Transport/protocol: compatible with raw asyncio protocols. Threads: loop.run_in_executor. Selector: uvloop replaces the selector event loop with libuv’s I/O poller. Platform: Linux and macOS only (not Windows). Performance: 2–4× faster than default asyncio for I/O-heavy workloads. uvloop.new_event_loop() — create a loop instance manually. loop.run_until_complete(coro). loop.run_forever(). Claude Code generates uvloop-accelerated FastAPI servers, aiohttp services, asyncpg database workers, and benchmarking harnesses.

CLAUDE.md for uvloop

## uvloop Stack
- Version: uvloop >= 0.19 | pip install uvloop
- Install: uvloop.install() at module top (before asyncio imports complete)
- Policy: asyncio.set_event_loop_policy(uvloop.EventLoopPolicy())
- Run: uvloop.run(main()) — equivalent to asyncio.run() with uvloop
- Uvicorn: uvicorn myapp:app --loop uvloop (default when uvloop installed)
- Platform: Linux + macOS only (no Windows support)

uvloop Async Performance Pipeline

# app/fast_loop.py — uvloop installation, benchmarking, aiohttp, asyncpg patterns
from __future__ import annotations

import asyncio
import statistics
import time
from contextlib import asynccontextmanager
from typing import Any, AsyncGenerator, Callable, Coroutine

import uvloop


# ─────────────────────────────────────────────────────────────────────────────
# 1. Installation helpers
# ─────────────────────────────────────────────────────────────────────────────

def install(force: bool = False) -> bool:
    """
    Install uvloop as the global asyncio event loop policy.
    Must be called before asyncio.run() or any loop creation.

    Returns True if uvloop is now active, False if already set (or force skipped).

    Usage (top of main.py or app/__init__.py):
        from app.fast_loop import install
        install()
    """
    policy = asyncio.get_event_loop_policy()
    if isinstance(policy, uvloop.EventLoopPolicy) and not force:
        return False  # Already installed
    asyncio.set_event_loop_policy(uvloop.EventLoopPolicy())
    return True


def run(coro: Coroutine, *, debug: bool = False) -> Any:
    """
    Drop-in replacement for asyncio.run() that uses uvloop.
    Equivalent to asyncio.run(coro) but with the uvloop event loop.

    Usage:
        uvloop_run(main())
    """
    return uvloop.run(coro, debug=debug)


def new_loop() -> uvloop.Loop:
    """Create a new uvloop event loop instance."""
    return uvloop.new_event_loop()


def active_loop_name() -> str:
    """Return the class name of the running event loop."""
    try:
        loop = asyncio.get_running_loop()
        return type(loop).__name__
    except RuntimeError:
        return "no running loop"


def is_uvloop_active() -> bool:
    """Check whether uvloop is the currently active policy."""
    return isinstance(asyncio.get_event_loop_policy(), uvloop.EventLoopPolicy)


# ─────────────────────────────────────────────────────────────────────────────
# 2. Benchmarking helpers
# ─────────────────────────────────────────────────────────────────────────────

async def _bench_once(
    coro_factory: Callable[[], Coroutine],
    concurrency: int = 100,
) -> float:
    """Run `concurrency` coroutines concurrently and return elapsed seconds."""
    start = time.perf_counter()
    await asyncio.gather(*[coro_factory() for _ in range(concurrency)])
    return time.perf_counter() - start


async def benchmark(
    coro_factory: Callable[[], Coroutine],
    concurrency: int = 100,
    rounds: int = 5,
    warmup: int = 1,
    label: str = "task",
) -> dict[str, float]:
    """
    Benchmark an async workload under uvloop.
    coro_factory:  zero-arg callable that returns a fresh coroutine each call.
    concurrency:   tasks per round.
    rounds:        measured rounds (after warmup).
    warmup:        un-measured warm-up rounds.

    Returns dict with min/max/median/mean elapsed seconds and ops/sec.

    Example:
        async def fetch():
            async with session.get("http://localhost/ping") as r:
                await r.read()

        stats = await benchmark(fetch, concurrency=500, rounds=5)
        print(f"median latency: {stats['median_ms']:.1f}ms  ops/sec: {stats['ops_per_sec']:.0f}")
    """
    for _ in range(warmup):
        await _bench_once(coro_factory, concurrency)

    times: list[float] = []
    for _ in range(rounds):
        elapsed = await _bench_once(coro_factory, concurrency)
        times.append(elapsed)

    return {
        "label":       label,
        "concurrency": concurrency,
        "rounds":      rounds,
        "min_ms":      min(times) * 1000,
        "max_ms":      max(times) * 1000,
        "median_ms":   statistics.median(times) * 1000,
        "mean_ms":     statistics.mean(times) * 1000,
        "ops_per_sec": (concurrency * rounds) / sum(times),
        "loop":        active_loop_name(),
    }


async def compare_loops(
    coro_factory: Callable[[], Coroutine],
    concurrency: int = 200,
    rounds: int = 3,
    label: str = "workload",
) -> dict[str, dict]:
    """
    Compare uvloop vs default asyncio event loop for the same workload.
    Returns {"uvloop": stats, "asyncio": stats}.

    Note: switches policy back and forth — not safe in production,
    use only for benchmarking scripts.

    Example:
        results = await compare_loops(lambda: asyncio.sleep(0), concurrency=1000)
        speedup = results["asyncio"]["median_ms"] / results["uvloop"]["median_ms"]
        print(f"uvloop is {speedup:.2f}x faster")
    """
    results: dict[str, dict] = {}

    # Benchmark with uvloop
    asyncio.set_event_loop_policy(uvloop.EventLoopPolicy())
    results["uvloop"] = await benchmark(coro_factory, concurrency, rounds, label=label)

    # Benchmark with default asyncio
    asyncio.set_event_loop_policy(asyncio.DefaultEventLoopPolicy())
    results["asyncio"] = await benchmark(coro_factory, concurrency, rounds, label=label)

    # Restore uvloop
    asyncio.set_event_loop_policy(uvloop.EventLoopPolicy())
    return results


# ─────────────────────────────────────────────────────────────────────────────
# 3. aiohttp server pattern
# ─────────────────────────────────────────────────────────────────────────────

AIOHTTP_EXAMPLE = '''
# Install uvloop before creating the app
import uvloop
uvloop.install()

from aiohttp import web

async def handle(request):
    return web.Response(text="Hello, uvloop!")

async def health(request):
    return web.json_response({"status": "ok", "loop": type(asyncio.get_running_loop()).__name__})

app = web.Application()
app.router.add_get("/", handle)
app.router.add_get("/health", health)

if __name__ == "__main__":
    # uvloop.install() already called above — aiohttp uses it automatically
    web.run_app(app, host="0.0.0.0", port=8080)
'''


# ─────────────────────────────────────────────────────────────────────────────
# 4. FastAPI + uvicorn pattern
# ─────────────────────────────────────────────────────────────────────────────

FASTAPI_EXAMPLE = '''
# FastAPI with uvicorn — uvloop is used automatically when installed
# Install uvloop: pip install uvloop

# main.py
import uvloop
uvloop.install()  # must be before any asyncio.run / uvicorn start

from contextlib import asynccontextmanager
from fastapi import FastAPI
import asyncio

@asynccontextmanager
async def lifespan(app: FastAPI):
    loop_name = type(asyncio.get_running_loop()).__name__
    print(f"Starting with event loop: {loop_name}")
    yield

app = FastAPI(lifespan=lifespan)

@app.get("/health")
async def health():
    return {"loop": type(asyncio.get_running_loop()).__name__}

# Run with: uvicorn main:app --loop uvloop --host 0.0.0.0 --port 8000
# Or programmatically:
if __name__ == "__main__":
    import uvicorn
    uvicorn.run(app, host="0.0.0.0", port=8000, loop="uvloop")
'''


# ─────────────────────────────────────────────────────────────────────────────
# 5. asyncpg / database pattern
# ─────────────────────────────────────────────────────────────────────────────

ASYNCPG_EXAMPLE = '''
import uvloop
uvloop.install()  # asyncpg benefits significantly from uvloop

import asyncio
import asyncpg

DATABASE_URL = "postgresql://user:pass@localhost/mydb"

async def init_pool():
    return await asyncpg.create_pool(DATABASE_URL, min_size=5, max_size=20)

async def fetch_users(pool, limit=100):
    async with pool.acquire() as conn:
        return await conn.fetch("SELECT id, name, email FROM users LIMIT $1", limit)

async def main():
    pool = await init_pool()
    users = await fetch_users(pool)
    print(f"Fetched {len(users)} users with {type(asyncio.get_running_loop()).__name__}")
    await pool.close()

asyncio.run(main())  # Uses uvloop because uvloop.install() was called
'''


# ─────────────────────────────────────────────────────────────────────────────
# 6. Gunicorn deployment
# ─────────────────────────────────────────────────────────────────────────────

GUNICORN_EXAMPLE = '''
# gunicorn.conf.py — uvloop with gunicorn aiohttp worker
worker_class = "aiohttp.GunicornUVLoopWebWorker"
workers = 4
bind = "0.0.0.0:8000"
keepalive = 5
timeout = 30

# For FastAPI/ASGI with uvicorn workers:
# gunicorn myapp:app -w 4 -k uvicorn.workers.UvicornWorker --bind 0.0.0.0:8000
# Or for maximum performance with uvloop worker:
# pip install uvicorn[standard]  # includes uvloop
# gunicorn myapp:app -w 4 -k uvicorn.workers.UvicornWorker
'''


# ─────────────────────────────────────────────────────────────────────────────
# Demo
# ─────────────────────────────────────────────────────────────────────────────

async def _do_nothing():
    """Ultra-lightweight coroutine for event loop overhead benchmarking."""
    await asyncio.sleep(0)


async def _cpu_task(n: int = 10_000):
    """Simulate mixed async + CPU work."""
    total = sum(range(n))
    await asyncio.sleep(0)
    return total


async def demo():
    print(f"Active event loop: {active_loop_name()}")
    print(f"uvloop installed: {is_uvloop_active()}")

    print("\n=== Benchmarking asyncio.sleep(0) — 500 concurrent, 3 rounds ===")
    stats = await benchmark(lambda: asyncio.sleep(0), concurrency=500, rounds=3,
                            label="sleep(0)")
    print(f"  loop:      {stats['loop']}")
    print(f"  median:    {stats['median_ms']:.2f}ms")
    print(f"  ops/sec:   {stats['ops_per_sec']:.0f}")

    print("\n=== uvloop vs asyncio comparison (100 concurrent) ===")
    results = await compare_loops(lambda: asyncio.sleep(0), concurrency=100, rounds=3,
                                  label="sleep(0)")
    for name, r in results.items():
        print(f"  {name:8s}: median={r['median_ms']:.2f}ms  ops/sec={r['ops_per_sec']:.0f}")

    uv_med  = results["uvloop"]["median_ms"]
    aio_med = results["asyncio"]["median_ms"]
    if aio_med > 0:
        print(f"\n  uvloop speedup: {aio_med / uv_med:.2f}x")


if __name__ == "__main__":
    install()  # Set uvloop globally
    uvloop.run(demo())  # Run with uvloop

For the asyncio (default) alternative — Python’s built-in asyncio event loop uses a pure-Python selector implementation; uvloop replaces it with a C extension backed by libuv (the same event loop powering Node.js), giving 2–4× higher throughput for I/O-bound workloads with zero code changes beyond uvloop.install(). For the trio alternative — trio is a structured-concurrency async framework with scope-based cancellation, nurseries, and a focus on correctness; uvloop is not an alternative framework but a performance drop-in for the standard asyncio event loop — use uvloop when you want asyncio compatibility and better I/O throughput, trio when you want structured concurrency guarantees and checkpoints. The Claude Skills 360 bundle includes uvloop skill sets covering install()/run() helpers, is_uvloop_active()/active_loop_name() introspection, benchmark() concurrent workload timer, compare_loops() asyncio vs uvloop measurement, aiohttp uvloop integration, FastAPI+uvicorn loop=uvloop configuration, asyncpg connection pool pattern, Gunicorn aiohttp/uvicorn worker config, and new_loop() for manual loop management. Start with the free tier to try uvloop async performance optimization code generation.

Keep Reading

AI

Claude Code for email.contentmanager: Python Email Content Accessors

Read and write EmailMessage body content with Python's email.contentmanager module and Claude Code — email contentmanager ContentManager for the class that maps content types to get and set handler functions allowing EmailMessage to support get_content and set_content with type-specific behaviour, email contentmanager raw_data_manager for the ContentManager instance that handles raw bytes and str payloads without any conversion, email contentmanager content_manager for the standard ContentManager instance used by email.policy.default that intelligently handles text plain text html multipart and binary content types, email contentmanager get_content_text for the handler that returns the decoded text payload of a text-star message part as a str, email contentmanager get_content_binary for the handler that returns the raw decoded bytes payload of a non-text message part, email contentmanager get_data_manager for the get-handler lookup used by EmailMessage get_content to find the right reader function for the content type, email contentmanager set_content text for the handler that creates and sets a text part correctly choosing charset and transfer encoding, email contentmanager set_content bytes for the handler that creates and sets a binary part with base64 encoding and optional filename Content-Disposition, email contentmanager EmailMessage get_content for the method that reads the message body using the registered content manager handlers, email contentmanager EmailMessage set_content for the method that sets the message body and MIME headers in one call, email contentmanager EmailMessage make_alternative make_mixed make_related for the methods that convert a simple message into a multipart container, email contentmanager EmailMessage add_attachment for the method that attaches a file or bytes to a multipart message, and email contentmanager integration with email.message and email.policy and email.mime and io for building high-level email readers attachment extractors text body accessors HTML readers and policy-aware MIME construction pipelines.

5 min read Feb 12, 2029
AI

Claude Code for email.charset: Python Email Charset Encoding

Control header and body encoding for international email with Python's email.charset module and Claude Code — email charset Charset for the class that wraps a character set name with the encoding rules for header encoding and body encoding describing how to encode text for that charset in email messages, email charset Charset header_encoding for the attribute specifying whether headers using this charset should use QP quoted-printable encoding BASE64 encoding or no encoding, email charset Charset body_encoding for the attribute specifying the Content-Transfer-Encoding to use for message bodies in this charset such as QP or BASE64, email charset Charset output_codec for the attribute giving the Python codec name used to encode the string to bytes for the wire format, email charset Charset input_codec for the attribute giving the Python codec name used to decode incoming bytes to str, email charset Charset get_output_charset for returning the output charset name, email charset Charset header_encode for encoding a header string using the charset's header_encoding method, email charset Charset body_encode for encoding body content using the charset's body_encoding, email charset Charset convert for converting a string from the input_codec to the output_codec, email charset add_charset for registering a new charset with custom encoding rules in the global charset registry, email charset add_alias for adding an alias name that maps to an existing registered charset, email charset add_codec for registering a codec name mapping for use by the charset machinery, and email charset integration with email.message and email.mime and email.policy and email.encoders for building international email senders non-ASCII header encoders Content-Transfer-Encoding selectors charset-aware message constructors and MIME encoding pipelines.

5 min read Feb 11, 2029
AI

Claude Code for email.utils: Python Email Address and Header Utilities

Parse and format RFC 2822 email addresses and dates with Python's email.utils module and Claude Code — email utils parseaddr for splitting a display-name plus angle-bracket address string into a realname and email address tuple, email utils formataddr for combining a realname and address string into a properly quoted RFC 2822 address with angle brackets, email utils getaddresses for parsing a list of raw address header strings each potentially containing multiple comma-separated addresses into a list of realname address tuples, email utils parsedate for parsing an RFC 2822 date string into a nine-tuple compatible with time.mktime, email utils parsedate_tz for parsing an RFC 2822 date string into a ten-tuple that includes the UTC offset timezone in seconds, email utils parsedate_to_datetime for parsing an RFC 2822 date string into an aware datetime object with timezone, email utils formatdate for formatting a POSIX timestamp or the current time as an RFC 2822 date string with optional usegmt and localtime flags, email utils format_datetime for formatting a datetime object as an RFC 2822 date string, email utils make_msgid for generating a globally unique Message-ID string with optional idstring and domain components, email utils decode_rfc2231 for decoding an RFC 2231 encoded parameter value into a tuple of charset language and value, email utils encode_rfc2231 for encoding a string as an RFC 2231 encoded parameter value, email utils collapse_rfc2231_value for collapsing a decoded RFC 2231 tuple to a Unicode string, and email utils integration with email.message and email.headerregistry and datetime and time for building address parsers date formatters message-id generators header extractors and RFC-compliant email construction utilities.

5 min read Feb 10, 2029

Put these ideas into practice

Claude Skills 360 gives you production-ready skills for everything in this article — and 2,350+ more. Start free or go all-in.

Back to Blog

Get 360 skills free