> Every page of the ganymede website is listed in https://eugo.io/docs/ganymede/llms.txt.

# Uvloop

> Uvloop: A fast, drop-in replacement for the built-in asyncio event loop, built on libuv. A Python demo notebook from ganymede.

Web page: https://eugo.io/docs/ganymede/demo_notebooks/data_storage/databases/utilities/uvloop/
Notebook: https://eugo.io/docs/ganymede/demo_notebooks/data_storage/databases/utilities/uvloop/uvloop.ipynb (source: https://github.com/eugo-inc/ganymede/blob/main/demo_notebooks/data_storage/databases/utilities/uvloop.ipynb)

Description:
- A fast, drop-in replacement for the built-in asyncio event loop, built on libuv.

Resources:
- https://github.com/MagicStack/uvloop/
- https://github.com/MagicStack/uvloop/tree/master/examples/bench
- https://uvloop.readthedocs.io/
- https://github.com/MagicStack/uvloop/wiki

## Setup

Jupyter already runs an asyncio event loop in the kernel's main thread, so `uvloop.run()` and `asyncio.Runner` cannot start a second loop there. The helper below runs them in a worker thread instead. In a plain Python script, call them directly.

```python
import asyncio
import concurrent.futures

import uvloop


def run_in_thread(fn, *args):
    """Run fn(*args) in a worker thread and return its result."""
    with concurrent.futures.ThreadPoolExecutor(max_workers=1) as pool:
        return pool.submit(fn, *args).result()
```

## Example 1

Run a coroutine on a new uvloop event loop with `uvloop.run()`

```python
async def main():
    loop = asyncio.get_running_loop()
    print("hello from", type(loop).__module__, type(loop).__name__)

# uvloop.run() creates a uvloop event loop, runs main() on it and closes the loop
run_in_thread(uvloop.run, main())
```

## Example 2

Use `asyncio.Runner` with uvloop's loop factory (Python 3.11 and newer), or `uvloop.install()` on older versions

```python
import sys

async def main():
    print("hello!")

def run_with_runner():
    if sys.version_info >= (3, 11):
        with asyncio.Runner(loop_factory=uvloop.new_event_loop) as runner:
            runner.run(main())
    else:
        uvloop.install()
        asyncio.run(main())

run_in_thread(run_with_runner)
```

## Example 3

Start a small TCP echo server on a uvloop loop, send it two messages from a client on the same loop, and stop. For throughput benchmarks, see uvloop's bench scripts (linked above).

```python
async def handle_echo(reader, writer):
    # Echo every line back to the client until it disconnects
    while data := await reader.readline():
        writer.write(data)
        await writer.drain()
    writer.close()
    await writer.wait_closed()


async def echo_round_trip(messages):
    # Port 0 lets the operating system pick a free port
    server = await asyncio.start_server(handle_echo, "127.0.0.1", 0)
    host, port = server.sockets[0].getsockname()[:2]
    print(f"Echo server on {host}:{port}, event loop: {type(asyncio.get_running_loop()).__name__}")

    async with server:
        reader, writer = await asyncio.open_connection(host, port)
        for message in messages:
            writer.write(message.encode() + b"\n")
            await writer.drain()
            reply = await reader.readline()
            print(f"sent {message!r}, got back {reply.decode().rstrip()!r}")
        writer.close()
        await writer.wait_closed()


run_in_thread(uvloop.run, echo_round_trip(["hello", "uvloop"]))
```
