asyncio-atexit

1.0.1 · active · verified Wed Apr 15

asyncio-atexit is a Python library that provides `atexit`-like functionality for `asyncio` event loops. It allows users to register coroutines or synchronous functions to be executed when the current `asyncio` event loop closes, rather than when the Python interpreter exits. The current version is 1.0.1, and it is a small utility that is updated infrequently but remains active and functional for its specific purpose.

Warnings

Install

Imports

Quickstart

Registers an asynchronous function and a synchronous function to be called when the asyncio event loop shuts down. This example demonstrates using `functools.partial` to pass arguments to the cleanup functions, as `asyncio-atexit` callbacks are invoked without arguments by default. The `asyncio.run` function typically manages loop closure, but an explicit `loop.close()` is added in the `finally` block to guarantee cleanup function execution in all environments for demonstration purposes.

import asyncio
import asyncio_atexit
import functools

async def async_cleanup_task(resource_name):
    print(f"Async cleanup for {resource_name} started...")
    await asyncio.sleep(0.1) # Simulate async work
    print(f"Async cleanup for {resource_name} finished.")

def sync_cleanup_task(message):
    print(f"Sync cleanup: {message}")

async def main():
    print("Main application started.")
    # Register an async cleanup task
    asyncio_atexit.register(functools.partial(async_cleanup_task, "Database Connection"))
    # Register a synchronous cleanup task
    asyncio_atexit.register(functools.partial(sync_cleanup_task, "Closing log file."))
    print("Cleanup tasks registered.")
    await asyncio.sleep(0.5) # Simulate main application work
    print("Main application finishing.")

if __name__ == '__main__':
    try:
        asyncio.run(main())
    finally:
        # In some scenarios, especially with older asyncio.run or specific policies,
        # you might explicitly close the loop if it wasn't handled by asyncio.run.
        # asyncio-atexit hooks only run if the event loop is actually closed.
        # This ensures the example triggers the atexit hooks.
        loop = asyncio.get_event_loop()
        if not loop.is_closed():
            loop.close()

view raw JSON →