Python Glossary Русский

Python 3.4+Async programmingfunction

asyncio.ensure_future()

tasks

Turns an awaitable into a Future: a coroutine is wrapped in a task, while a Future or Task is returned unchanged.

Syntax

fut = asyncio.ensure_future(obj, *, loop=None)

For your own code the docs recommend create_task: it accepts only coroutines and says plainly that it creates a task. ensure_future is for libraries that receive "anything awaitable" and want a single Future. The trap is calling it without a running loop: on 3.12–3.13 that is a DeprecationWarning with the loop picked implicitly, and since 3.14 it raises RuntimeError. As with any task, keep a reference or it may be garbage-collected.

Examples

import asyncio
async def job():
    return 5
async def main():
    fut = asyncio.get_running_loop().create_future()
    print(asyncio.ensure_future(fut) is fut)  # → True — Future не трогается
    task = asyncio.ensure_future(job())
    print(type(task).__name__, await task)  # → Task 5
    fut.cancel()
asyncio.run(main())

See also

Open in the full glossarydocs.python.orgReport an inaccuracy