uvloop

repository·master·Indexed 11 days ago

https://github.com/magicstack/uvloop

A high-performance, drop-in replacement for the built-in asyncio event loop implemented in Cython and built on top of libuv. It provides the same interface as asyncio.AbstractEventLoop, making asyncio 2-4x faster. Key features include the uvloop.run() helper for managing coroutine lifecycles and integration with asyncio.Runner for Python 3.11+.

Tokens
2.1K
Snippets
12
Records
15
Agent score
92%

What's inside uvloop

  1. What is uvloop and how does it work?

    master

    uvloop is a high-performance, drop-in replacement for the built-in Python asyncio event loop. It is designed to make asyncio significantly faster—often reaching performance levels close to Go programs and outperforming Node.js or gevent.

    Key Characteristics

    • Compatibility: It implements the asyncio.AbstractEventLoop interface, making it a drop-in replacement for the standard asyncio loop.
    • Implementation: It is written in Cython and built on top of libuv, the same high-performance, multiplatform asynchronous I/O library used by Node.js.
    • Functionality: It provides all standard asyncio event loop APIs, including scheduling calls, network data transmission, DNS queries, OS signal handling, server/connection abstractions, and asynchronous subprocess management.
  2. Use uvloop as the default asyncio event loop policy

    master

    To make the standard asyncio library use uvloop globally for your application, install the uvloop.EventLoopPolicy(). This is the recommended way to swap the default asyncio event loop with uvloop.

    import asyncio
    import uvloop
    asyncio.set_event_loop_policy(uvloop.EventLoopPolicy())
  3. Run uvloop unit tests

    master

    You can run the full test suite using make test, which runs the standard library unittest tool twice: once with PYTHONASYNCIODEBUG enabled and once without.

    $ cd uvloop
    $ make test

    To run individual tests, it is easiest to first install the package in editable mode using pip so that uvloop is discoverable by the Python path:

    $ cd uvloop
    $ pip install -e .

    Then, run specific tests using unittest or pytest from the tests directory:

    Using unittest:

    $ cd uvloop/tests
    $ python -m unittest test_tcp

    Using pytest:

    $ cd uvloop/tests
    $ py.test -k test_signals_sigint_uvcode
  4. Replace the standard asyncio event loop with uvloop

    master

    To use uvloop as the event loop implementation for your application, you should use uvloop.install(). This sets uvloop as the default event loop policy for the current process, ensuring that any subsequent calls to asyncio.get_event_loop() or asyncio.run() use the high-performance uvloop.Loop instead of the standard library implementation.

    import asyncio
    import uvloop
    
    async def main():
        # Your asyncio code here
        pass
    
    if __name__ == '__main__':
        uvloop.install()
        asyncio.run(main())
  5. Build uvloop from source

    master

    To build uvloop from source, you need Cython and Python 3.8 or newer. It is recommended to use a virtual environment to ensure the correct tools are used.

    1. Clone the repository recursively to include libuv:
      git clone --recursive git@github.com:MagicStack/uvloop.git
    2. Create and activate a virtual environment:
      python3 -m venv myvenv
      source myvenv/bin/activate
    3. Install Cython:
      pip install Cython
    4. Build using make from the top-level directory:
      cd uvloop
      make
    $ python3 -m venv myvenv
    $ source myvenv/bin/activate
    $ pip install Cython
    $ cd uvloop
    $ make
  6. Use uvloop with uvloop.run()

    master

    As of uvloop 0.18, the preferred way to use uvloop is via the uvloop.run() helper function. This function configures asyncio.run() to use the uvloop event loop and passes all arguments (such as debug) directly to it.

    import uvloop
    
    async def main():
        # Main entry-point.
        ...
    
    uvloop.run(main())
    
    # You can also pass arguments like debug:
    uvloop.run(main(), debug=True)
  7. Rebuild project documentation

    master

    To rebuild the Sphinx HTML documentation, you must have sphinx installed. You can install it via pip and then run the make docs command from the top-level directory.

    1. Install Sphinx:
      pip install sphinx
    2. Build documentation:
      make docs
    $ pip install sphinx
    $ make docs
  8. Use uvloop with asyncio.Runner (Python 3.11+)

    master

    For Python 3.11 and later, you can use asyncio.Runner with the loop_factory argument set to uvloop.new_event_loop to integrate uvloop into the standard asyncio runner lifecycle.

    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())
  9. Create a new uvloop instance with new_event_loop()

    master

    If you need to create a specific instance of a uvloop.Loop without changing the global event loop policy, use uvloop.new_event_loop(). This returns a new uvloop.Loop object.

    import uvloop
    
    loop = uvloop.new_event_loop()
    # Use the loop explicitly
  10. Create and set a uvloop instance manually

    master

    If you need to manage the event loop instance directly, you can create a new loop using uvloop.new_event_loop() and then set it as the current event loop using asyncio.set_event_loop().

    import asyncio
    import uvloop
    loop = uvloop.new_event_loop()
    asyncio.set_event_loop(loop)
  11. Run a coroutine with uvloop.run()

    master

    The preferred way to run a coroutine using uvloop is via the uvloop.run() function. This function manages the event loop lifecycle, including creation, execution, and proper shutdown of tasks and generators. It is compatible with different Python versions by utilizing asyncio.Runner or asyncio.run internally.

    Parameters:

    • main: The coroutine to be executed.
    • loop_factory: A callable that returns a new event loop. Defaults to uvloop.new_event_loop.
    • debug: An optional boolean to enable/disable asyncio debug mode.
    • **run_kwargs: Additional keyword arguments passed to the underlying asyncio runner.
    import uvloop
    import asyncio
    
    async def main():
        print("Hello from uvloop!")
        await asyncio.sleep(1)
    
    if __name__ == "__main__":
        uvloop.run(main())