Uvloop¶
Description:
- A fast, drop-in replacement for the built-in asyncio event loop, built on libuv.
Resources:
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.
In [ ]:
Copied!
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()
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()
In [ ]:
Copied!
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())
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
In [ ]:
Copied!
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)
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).
In [ ]:
Copied!
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"]))
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"]))