Utility to detect blocking calls in the async event loop

1.5.26 · active · verified Thu Apr 09

Blockbuster is a Python package designed to detect and prevent blocking calls within an asynchronous event loop. It's particularly useful during testing to ensure asynchronous code doesn't inadvertently perform blocking operations, which can cause performance bottlenecks. It works by monkey-patching common blocking functions and raising a `BlockingError` if called within an `asyncio` event loop. It currently only detects `asyncio` event loops and is tested with CPython.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to use `blockbuster_ctx` to detect blocking calls within an `asyncio` event loop. It runs an `async` function that intentionally calls `time.sleep()`, which is a blocking operation. When `blockbuster_ctx` is active, this call will raise a `BlockingError`. The second part shows the same blocking call without `blockbuster` activated, which completes without error, highlighting the utility of the library.

import asyncio
import time
from blockbuster import blockbuster_ctx, BlockingError

async def main():
    print("Running async task with blockbuster (should fail on time.sleep)...")
    try:
        with blockbuster_ctx():
            # This is a blocking call and should raise BlockingError
            time.sleep(0.1)
        print("This line should not be reached if blocking call is detected.")
    except BlockingError as e:
        print(f"Caught expected BlockingError: {e}")
    except Exception as e:
        print(f"Caught unexpected error: {e}")

    print("\nRunning async task without blockbuster (should complete)...")
    try:
        # This will complete without error
        time.sleep(0.1)
        print("Blocking call completed without blockbuster activated.")
    except BlockingError as e:
        print(f"Caught BlockingError (unexpected): {e}")

if __name__ == "__main__":
    asyncio.run(main())

view raw JSON →