KennisbankExamencentrum
NL · NLNederlands (Nederland)
Taal kiezen13

CKTIS / Python

contextlib.AbstractAsyncContextManager

Vereenvoudigt het implementeren van async with.

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

Syntax

class Scope(contextlib.AbstractAsyncContextManager): ...

Vereenvoudigt het implementeren van async with.

De geërfde __aenter__ geeft na await self en de subklasse moet een asynchrone __aexit__ definiëren. Deze krijgt bij succes drie keer None en anders type, uitzondering en traceback. Een waar resultaat onderdrukt de uitzondering.

Hier laat False ValueError de buitenste afhandeling bereiken.

import asyncio
from contextlib import AbstractAsyncContextManager
seen = []
class Scope(AbstractAsyncContextManager):
    async def __aexit__(self, typ, value, tb):
        seen.append((typ, value, tb))
        return False
async def main():
    s = Scope()
    async with s as obj:
        assert obj is s
    assert seen == [(None, None, None)]
asyncio.run(main())

Voorbeelden

import contextlib
import asyncio

class Scope(contextlib.AbstractAsyncContextManager):
    async def __aexit__(self, kind, value, tb):
        print(kind.__name__ if kind is not None else "ok")
        return False

async def main():
    scope = Scope()
    try:
        async with scope as seen:
            print(seen is scope)
            raise ValueError
    except ValueError:
        print("caught")

asyncio.run(main())

Resultaat

True
ValueError
caught

Hier laat False ValueError de buitenste afhandeling bereiken.

Bronnen