Convert Figma logo to code with AI

MagicStack logouvloop

Ultra fast asyncio event loop.

10,269
537
10,269
109

Top Related Projects

23,916

Cross-platform asynchronous I/O

26,366

A runtime for writing reliable asynchronous applications with Rust. Provides I/O, networking, scheduling, timers, ...

14,938

Asynchronous HTTP client/server framework for asyncio and Python

6,078

Trio – a friendly Python library for async concurrency and I/O

4,024

Good Curio!

6,229

Coroutine-based concurrency library for Python

Quick Overview

uvloop is a fast, drop-in replacement for the asyncio event loop in Python. It's implemented in Cython and uses libuv under the hood, providing significant performance improvements over the standard asyncio loop.

Pros

  • Significantly faster than the default asyncio event loop
  • Easy to integrate into existing asyncio-based projects
  • Compatible with most asyncio libraries and frameworks
  • Well-maintained and actively developed

Cons

  • Only works on Unix-like systems (Linux, macOS, etc.), not Windows
  • Requires compilation, which can be an issue in some deployment scenarios
  • May introduce subtle behavioral differences compared to the standard asyncio loop
  • Limited debugging capabilities compared to the default asyncio loop

Code Examples

  1. Basic usage:
import asyncio
import uvloop

async def main():
    print("Hello, uvloop!")

uvloop.install()
asyncio.run(main())
  1. TCP echo server:
import asyncio
import uvloop

async def handle_echo(reader, writer):
    data = await reader.read(100)
    writer.write(data)
    await writer.drain()
    writer.close()

async def main():
    server = await asyncio.start_server(handle_echo, '127.0.0.1', 8888)
    async with server:
        await server.serve_forever()

uvloop.install()
asyncio.run(main())
  1. HTTP client example:
import asyncio
import uvloop
import aiohttp

async def fetch(url):
    async with aiohttp.ClientSession() as session:
        async with session.get(url) as response:
            return await response.text()

async def main():
    result = await fetch('https://example.com')
    print(result[:100])

uvloop.install()
asyncio.run(main())

Getting Started

To use uvloop in your project, follow these steps:

  1. Install uvloop:

    pip install uvloop
    
  2. Import and install uvloop at the beginning of your main script:

    import asyncio
    import uvloop
    
    uvloop.install()
    
  3. Use asyncio as you normally would. uvloop will automatically replace the default event loop with its high-performance implementation.

Competitor Comparisons

23,916

Cross-platform asynchronous I/O

Pros of libuv

  • Cross-platform support for asynchronous I/O
  • Widely used and battle-tested in production environments
  • Extensive feature set beyond just event loop functionality

Cons of libuv

  • Written in C, which can be more challenging to work with
  • Requires manual memory management
  • Steeper learning curve for developers not familiar with low-level programming

Code Comparison

uvloop (Python):

import asyncio
import uvloop

asyncio.set_event_loop_policy(uvloop.EventLoopPolicy())
asyncio.run(main())

libuv (C):

#include <uv.h>

int main() {
    uv_loop_t *loop = malloc(sizeof(uv_loop_t));
    uv_loop_init(loop);
    uv_run(loop, UV_RUN_DEFAULT);
    uv_loop_close(loop);
    free(loop);
    return 0;
}

Key Differences

  • uvloop is a Python implementation of the event loop using Cython, while libuv is a C library
  • uvloop is designed specifically for Python asyncio, whereas libuv is a more general-purpose library
  • uvloop aims to be a drop-in replacement for the asyncio event loop, making it easier to integrate into existing Python projects
  • libuv offers more low-level control and is used as a foundation for many other projects, including Node.js
26,366

A runtime for writing reliable asynchronous applications with Rust. Provides I/O, networking, scheduling, timers, ...

Pros of tokio

  • Written in Rust, offering memory safety and zero-cost abstractions
  • Supports both asynchronous I/O and CPU-bound tasks
  • Extensive ecosystem with many compatible libraries

Cons of tokio

  • Steeper learning curve due to Rust's complexity
  • Potentially slower compilation times compared to Python
  • Less mature than uvloop, which is based on the well-established libuv

Code Comparison

uvloop (Python):

import asyncio
import uvloop

asyncio.set_event_loop_policy(uvloop.EventLoopPolicy())

async def main():
    await asyncio.sleep(1)

asyncio.run(main())

tokio (Rust):

use tokio;

#[tokio::main]
async fn main() {
    tokio::time::sleep(std::time::Duration::from_secs(1)).await;
}

Both libraries aim to provide high-performance asynchronous I/O, but they target different languages and ecosystems. uvloop enhances Python's asyncio with libuv, while tokio offers a comprehensive async runtime for Rust. The choice between them largely depends on the preferred programming language and specific project requirements.

14,938

Asynchronous HTTP client/server framework for asyncio and Python

Pros of aiohttp

  • Full-featured HTTP client/server framework for asyncio
  • Supports both client and server-side HTTP operations
  • Extensive documentation and active community support

Cons of aiohttp

  • Generally slower performance compared to uvloop
  • More complex API for basic HTTP operations

Code Comparison

aiohttp example:

import aiohttp
import asyncio

async def fetch(session, url):
    async with session.get(url) as response:
        return await response.text()

async def main():
    async with aiohttp.ClientSession() as session:
        html = await fetch(session, 'http://python.org')
        print(html)

asyncio.run(main())

uvloop example:

import asyncio
import uvloop

async def main():
    await asyncio.sleep(1)
    print("Hello, uvloop!")

uvloop.install()
asyncio.run(main())

Key Differences

  • aiohttp is a high-level HTTP framework, while uvloop is a drop-in replacement for asyncio's event loop
  • uvloop focuses on performance optimization, while aiohttp provides a comprehensive HTTP toolkit
  • aiohttp is more suitable for complex HTTP applications, while uvloop enhances overall asyncio performance

Use Cases

  • Choose aiohttp for building HTTP clients/servers or web applications
  • Use uvloop to boost performance of existing asyncio-based applications

Community and Ecosystem

Both projects have active communities and are well-maintained, but aiohttp has a larger ecosystem of extensions and plugins due to its broader scope.

6,078

Trio – a friendly Python library for async concurrency and I/O

Pros of trio

  • Designed for structured concurrency, making it easier to reason about and manage concurrent code
  • Provides built-in cancellation and timeout support, enhancing robustness
  • Offers a more Pythonic API, focusing on simplicity and readability

Cons of trio

  • Generally slower performance compared to uvloop
  • Less mature ecosystem and fewer third-party libraries
  • Requires rewriting existing asyncio-based code to use trio's API

Code Comparison

trio:

import trio

async def main():
    async with trio.open_nursery() as nursery:
        nursery.start_soon(task1)
        nursery.start_soon(task2)

trio.run(main)

uvloop:

import asyncio
import uvloop

asyncio.set_event_loop_policy(uvloop.EventLoopPolicy())

async def main():
    await asyncio.gather(task1(), task2())

asyncio.run(main())

The trio example demonstrates its structured concurrency approach with nurseries, while uvloop uses standard asyncio patterns with enhanced performance.

4,024

Good Curio!

Pros of Curio

  • Pure Python implementation, making it easier to understand and modify
  • Simpler API design, focusing on coroutines and tasks
  • Better integration with standard Python debugging tools

Cons of Curio

  • Generally slower performance compared to uvloop
  • Less widespread adoption and community support
  • Fewer built-in networking primitives and optimizations

Code Comparison

Curio example:

import curio

async def hello():
    await curio.sleep(1)
    print('Hello, World!')

curio.run(hello)

uvloop example:

import asyncio
import uvloop

async def hello():
    await asyncio.sleep(1)
    print('Hello, World!')

uvloop.install()
asyncio.run(hello())

Both Curio and uvloop aim to improve Python's asynchronous programming capabilities, but they take different approaches. Curio focuses on simplicity and pure Python implementation, while uvloop emphasizes performance by leveraging libuv. The choice between them depends on specific project requirements, with Curio being more suitable for educational purposes and simpler applications, while uvloop is better for high-performance scenarios.

6,229

Coroutine-based concurrency library for Python

Pros of gevent

  • Mature and widely adopted library with a large ecosystem
  • Supports a broader range of Python versions, including older ones
  • Provides monkey patching for seamless integration with existing code

Cons of gevent

  • Generally slower performance compared to uvloop
  • More complex implementation due to its use of greenlets
  • Can introduce subtle bugs when monkey patching is used incorrectly

Code Comparison

gevent example:

import gevent

def foo():
    print("Running in foo")
    gevent.sleep(0)
    print("Explicit context switch to foo again")

gevent.joinall([
    gevent.spawn(foo),
    gevent.spawn(foo),
])

uvloop example:

import asyncio
import uvloop

async def foo():
    print("Running in foo")
    await asyncio.sleep(0)
    print("Explicit context switch to foo again")

asyncio.set_event_loop_policy(uvloop.EventLoopPolicy())
asyncio.run(asyncio.gather(foo(), foo()))

Key Differences

  • gevent uses greenlets and monkey patching, while uvloop is built on top of libuv and integrates with Python's asyncio
  • uvloop generally offers better performance, especially for I/O-bound operations
  • gevent has a larger ecosystem and more third-party library support
  • uvloop requires Python 3.7+ and uses native coroutines, while gevent supports older Python versions and uses greenlets

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

.. image:: https://img.shields.io/github/actions/workflow/status/MagicStack/uvloop/tests.yml?branch=master :target: https://github.com/MagicStack/uvloop/actions/workflows/tests.yml?query=branch%3Amaster

.. image:: https://img.shields.io/pypi/v/uvloop.svg :target: https://pypi.python.org/pypi/uvloop

.. image:: https://pepy.tech/badge/uvloop :target: https://pepy.tech/project/uvloop :alt: PyPI - Downloads

uvloop is a fast, drop-in replacement of the built-in asyncio event loop. uvloop is implemented in Cython and uses libuv under the hood.

The project documentation can be found here <http://uvloop.readthedocs.org/>. Please also check out the wiki <https://github.com/MagicStack/uvloop/wiki>.

Performance

uvloop makes asyncio 2-4x faster.

.. image:: https://raw.githubusercontent.com/MagicStack/uvloop/master/performance.png :target: http://magic.io/blog/uvloop-blazing-fast-python-networking/

The above chart shows the performance of an echo server with different message sizes. The sockets benchmark uses loop.sock_recv() and loop.sock_sendall() methods; the streams benchmark uses asyncio high-level streams, created by the asyncio.start_server() function; and the protocol benchmark uses loop.create_server() with a simple echo protocol. Read more about uvloop in a blog post <http://magic.io/blog/uvloop-blazing-fast-python-networking/>_ about it.

Installation

uvloop requires Python 3.8 or greater and is available on PyPI. Use pip to install it::

$ pip install uvloop

Note that it is highly recommended to upgrade pip before installing uvloop with::

$ pip install -U pip

Using uvloop

As of uvloop 0.18, the preferred way of using it is via the uvloop.run() helper function:

.. code:: python

import uvloop

async def main():
    # Main entry-point.
    ...

uvloop.run(main())

uvloop.run() works by simply configuring asyncio.run() to use uvloop, passing all of the arguments to it, such as debug, e.g. uvloop.run(main(), debug=True).

With Python 3.11 and earlier the following alternative snippet can be used:

.. code:: python

import asyncio
import sys

import uvloop

async def main():
    # Main entry-point.
    ...

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())

Building From Source

To build uvloop, you'll need Python 3.8 or greater:

  1. Clone the repository:

    .. code::

    $ git clone --recursive git@github.com:MagicStack/uvloop.git $ cd uvloop

  2. Create a virtual environment and activate it:

    .. code::

    $ python3 -m venv uvloop-dev $ source uvloop-dev/bin/activate

  3. Install development dependencies:

    .. code::

    $ pip install -e .[dev]

  4. Build and run tests:

    .. code::

    $ make $ make test

License

uvloop is dual-licensed under MIT and Apache 2.0 licenses.