Python 3.6+sysfunction
sys.set_asyncgen_hooks()
asynchronous code
Installs the asynchronous generator hooks: firstiter runs on the first iteration, finalizer when the generator is garbage-collected.
Syntax
sys.set_asyncgen_hooks(firstiter=..., finalizer=...)
This is an API for event loop authors: asyncio, trio and uvloop install the hooks themselves, and overriding them from application code breaks generator cleanup. Hooks are per thread; an omitted argument leaves that hook unchanged. Save the old hooks and restore them.
Examples
import sys
seen = []
old = sys.get_asyncgen_hooks()
sys.set_asyncgen_hooks(firstiter=lambda agen: seen.append(agen.__name__))
async def ticks():
yield 1
g = ticks()
step = g.asend(None)
step.close()
sys.set_asyncgen_hooks(*old)
print(seen) # → ['ticks']
See also
Open in the full glossarydocs.python.orgReport an inaccuracy