KennisbankExamencentrum
NL · NLNederlands (Nederland)
Taal kiezen13

CKTIS / Python

asyncio.gather

Start coroutines gelijktijdig en levert na await een lijst in argumentvolgorde.

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

Syntax

asyncio.gather(*aws, return_exceptions=False)

Start coroutines gelijktijdig en levert na await een lijst in argumentvolgorde.

Standaard wordt de eerste uitzondering doorgegeven en gaan de overige taken door. Annulering van een wachtende gather annuleert onvoltooide kinderen.

Met return_exceptions=True neemt de uitzondering haar eigen plek in, vandaar 5 en ValueError.

import asyncio
async def main():
    gate = asyncio.Event()
    slow = asyncio.create_task(gate.wait())
    async def fail():
        raise ValueError("bad")
    try:
        await asyncio.gather(slow, fail())
    except ValueError:
        assert not slow.done()
    gate.set()
    assert await slow is True
asyncio.run(main())

Voorbeelden

import asyncio
async def fail():
    raise ValueError("sample")

async def main():
    results = await asyncio.gather(asyncio.sleep(0, result=5), fail(), return_exceptions=True)
    print(results[0], type(results[1]).__name__)

asyncio.run(main())

Resultaat

5 ValueError

Met return_exceptions=True neemt de uitzondering haar eigen plek in, vandaar 5 en ValueError.

Bronnen