Python Glossary Русский

Python 3.4+Async programmingfunction

asyncio.wrap_future()

threads interop

Wraps a concurrent.futures.Future (from a thread or process pool) in an asyncio.Future so it can be awaited.

Syntax

fut = asyncio.wrap_future(future, *, loop=None)

Awaiting a concurrent.futures.Future directly raises TypeError: it is a different class with a blocking result(). Usually loop.run_in_executor() does the wrapping for you; wrap_future is for a Future that came from other code, such as executor.submit(). Cancelling the wrapper tries to cancel the original Future, but a function already running in a thread is not stopped.

Examples

import asyncio
from concurrent.futures import ThreadPoolExecutor
async def main():
    with ThreadPoolExecutor() as pool:
        cf = pool.submit(sum, [1, 2, 3])
        try:
            await cf
        except TypeError:
            print('напрямую нельзя')  # → напрямую нельзя
        print(await asyncio.wrap_future(cf))  # → 6
asyncio.run(main())

See also

Open in the full glossarydocs.python.orgReport an inaccuracy