Base de connaissancesCentre d’examen
FRFrançais
Choisir la langue13

CKTIS / Python

contextlib.AbstractAsyncContextManager

Facilite la mise en œuvre de async with.

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

Syntaxe

class Scope(contextlib.AbstractAsyncContextManager): ...

Facilite la mise en œuvre de async with.

Le __aenter__ hérité renvoie self après await et la sous-classe doit fournir un __aexit__ asynchrone. Celui-ci reçoit trois None en cas de succès ou le type, l’exception et sa trace. Un résultat vrai supprime l’exception.

Ici False laisse ValueError atteindre le gestionnaire extérieur.

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())

Exemples

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())

Résultat

True
ValueError
caught

Ici False laisse ValueError atteindre le gestionnaire extérieur.

Sources