|
| 1 | +""" |
| 2 | +asyncio_atexit: atexit for asyncio |
| 3 | +""" |
| 4 | + |
| 5 | +import asyncio |
| 6 | +import inspect |
| 7 | +import sys |
| 8 | +import weakref |
| 9 | +from functools import partial |
| 10 | + |
| 11 | +__all__ = ["register", "unregister"] |
| 12 | +__version__ = "1.0.0.dev" |
| 13 | + |
| 14 | +_registry = weakref.WeakKeyDictionary() |
| 15 | + |
| 16 | +if sys.version_info < (3, 7): |
| 17 | + get_running_loop = asyncio.get_event_loop |
| 18 | +else: |
| 19 | + get_running_loop = asyncio.get_running_loop |
| 20 | + |
| 21 | + |
| 22 | +class _RegistryEntry: |
| 23 | + def __init__(self, loop): |
| 24 | + self._close_ref = weakref.WeakMethod(loop.close) |
| 25 | + self.callbacks = [] |
| 26 | + |
| 27 | + def close(self): |
| 28 | + return self._close_ref()() |
| 29 | + |
| 30 | + |
| 31 | +def register(callback, *, loop=None): |
| 32 | + """ |
| 33 | + Register a callback for when the current event loop closes |
| 34 | +
|
| 35 | + Like atexit.register, but run when the asyncio loop is closing, |
| 36 | + rather than process cleanup. |
| 37 | +
|
| 38 | + `loop` may be specified as a keyword arg |
| 39 | + to attach to a non-running event loop. |
| 40 | +
|
| 41 | + Allows coroutines to cleanup their resources. |
| 42 | +
|
| 43 | + Callback will be passed no arguments. |
| 44 | + To pass arguments to your callback, |
| 45 | + use `functools.partial`. |
| 46 | + """ |
| 47 | + entry = _get_entry(loop) |
| 48 | + entry.callbacks.append(callback) |
| 49 | + |
| 50 | + |
| 51 | +def unregister(callback, *, loop=None): |
| 52 | + """ |
| 53 | + Unregister a callback registered with asyncio_atexit.register |
| 54 | +
|
| 55 | + `loop` may be specified as a keyword arg |
| 56 | + to attach to a non-running event loop. |
| 57 | + """ |
| 58 | + |
| 59 | + entry = _get_entry(loop) |
| 60 | + # remove all instances of the callback |
| 61 | + while True: |
| 62 | + try: |
| 63 | + entry.callbacks.remove(callback) |
| 64 | + except ValueError: |
| 65 | + break |
| 66 | + |
| 67 | + |
| 68 | +def _get_entry(loop=None): |
| 69 | + """Get the registry entry for an event loop""" |
| 70 | + if loop is None: |
| 71 | + loop = get_running_loop() |
| 72 | + _register_loop(loop) |
| 73 | + return _registry[loop] |
| 74 | + |
| 75 | + |
| 76 | +def _register_loop(loop): |
| 77 | + """Patch an asyncio.EventLoop to support atexit callbacks""" |
| 78 | + if loop in _registry: |
| 79 | + return |
| 80 | + |
| 81 | + _registry[loop] = _RegistryEntry(loop) |
| 82 | + |
| 83 | + loop.close = partial(_asyncio_atexit_close, loop) |
| 84 | + |
| 85 | + |
| 86 | +async def _run_asyncio_atexits(loop, callbacks): |
| 87 | + """Run asyncio atexit callbacks |
| 88 | +
|
| 89 | + This runs in EventLoop.close() prior to actually closing the loop |
| 90 | + """ |
| 91 | + for callback in callbacks: |
| 92 | + try: |
| 93 | + f = callback() |
| 94 | + if inspect.isawaitable(f): |
| 95 | + await f |
| 96 | + except Exception as e: |
| 97 | + print( |
| 98 | + f"Unhandled exception in asyncio atexit callback {callback}: {e}", |
| 99 | + file=sys.stderr, |
| 100 | + ) |
| 101 | + |
| 102 | + |
| 103 | +def _asyncio_atexit_close(loop): |
| 104 | + """Patched EventLoop.close method to run atexit callbacks |
| 105 | +
|
| 106 | + prior to the unpatched close method. |
| 107 | + """ |
| 108 | + entry = _get_entry(loop) |
| 109 | + if entry.callbacks: |
| 110 | + loop.run_until_complete(_run_asyncio_atexits(loop, entry.callbacks)) |
| 111 | + entry.callbacks[:] = [] |
| 112 | + return entry.close() |
0 commit comments