Pyleak

0.2.0 · active · verified Thu Apr 16

Pyleak is a Python library inspired by Go's goleak, designed to detect leaked asyncio tasks, threads, and event loop blocking in asynchronous Python applications. The current version is 0.2.0, with frequent minor and patch releases, indicating active development.

Common errors

Warnings

Install

Imports

Quickstart

This example demonstrates how to use `LeakDetector` to identify unawaited or long-running asyncio tasks that are not properly shut down, which pyleak considers a leak. Running this code will raise an `AssertionError` at the end of the `async with LeakDetector():` block.

import asyncio
from pyleak import LeakDetector

async def create_leak():
    # A task that runs forever, simulating a leak
    async def forever_task():
        while True:
            await asyncio.sleep(100)
    asyncio.create_task(forever_task())

async def main():
    async with LeakDetector():
        await create_leak()
        print("This will run, but a leak was created.")
    # LeakDetector exits, will raise AssertionError if leaks are found
    print("LeakDetector exited, no assertion was raised (this line won't be reached if a leak is present).")

if __name__ == "__main__":
    # To see the AssertionError from the leak:
    # asyncio.run(main())
    
    # To avoid the assertion for demonstration:
    try:
        asyncio.run(main())
    except AssertionError as e:
        print(f"Caught expected leak: {e}")

view raw JSON →