Python 3.7+Async programmingfunction
asyncio.current_task()
introspection
Returns the Task that is running right now, or None when the code runs outside a task (for example in a plain loop callback).
Syntax
asyncio.current_task(loop=None)
Handy when a task needs to cancel itself, learn its own name or exclude itself from all_tasks(). Outside a running loop it raises RuntimeError rather than returning None: None means "the loop runs, but we are in a callback, not a task". Under asyncio.run() the main coroutine is wrapped in a task too, named like Task-1 by default.
Examples
import asyncio
async def worker():
print(asyncio.current_task().get_name()) # → загрузчик
async def main():
await asyncio.create_task(worker(), name='загрузчик')
loop = asyncio.get_running_loop()
loop.call_soon(lambda: print(asyncio.current_task())) # → None — колбэк, а не задача
await asyncio.sleep(0.01)
asyncio.run(main())
See also
Common errors
Open in the full glossarydocs.python.orgReport an inaccuracy