KennisbankExamencentrum
NL · NLNederlands (Nederland)
Taal kiezen13

CKTIS / Python

asyncio.wait

Neemt een niet-lege verzameling taken of Futures aan.

Versie: Python 3.14; repository image, production runtime not attested

Syntax

await asyncio.wait(aws, *, timeout=None, return_when=asyncio.ALL_COMPLETED)

Neemt een niet-lege verzameling taken of Futures aan.

Losse coroutineobjecten worden geweigerd. return_when kiest de eerste voltooiing, de eerste uitzondering of alle voltooiingen. Na een time-out volgen de verzamelingen done en pending zonder TimeoutError of annulering.

In het voorbeeld is één taak klaar en wacht de andere op het signaal.

import asyncio
async def main():
    loop = asyncio.get_running_loop()
    a, b = loop.create_future(), loop.create_future()
    a.set_result(2)
    done, pending = await asyncio.wait([a, b], return_when=asyncio.FIRST_COMPLETED)
    assert done == {a} and pending == {b} and not b.cancelled()
    b.cancel()
    try:
        await asyncio.wait([])
    except ValueError:
        pass
    else:
        raise AssertionError
asyncio.run(main())

Voorbeelden

import asyncio

async def main():
    gate = asyncio.Event()
    pending_task = asyncio.create_task(gate.wait())
    finished = asyncio.create_task(asyncio.sleep(0, result=5))
    await finished
    done, pending = await asyncio.wait([finished, pending_task], timeout=0)
    print(len(done), len(pending), pending_task.cancelled())
    gate.set()
    await pending_task

asyncio.run(main())

Resultaat

1 1 False

In het voorbeeld is één taak klaar en wacht de andere op het signaal.

Bronnen