Base de conocimientosCentro de exámenes
ESEspañol
Elegir idioma13

CKTIS / Python

contextlib.AbstractAsyncContextManager

Facilita la implementación de async with.

Versión: Python 3.14; repository image, production runtime not attested

Sintaxis

class Scope(contextlib.AbstractAsyncContextManager): ...

Facilita la implementación de async with.

El __aenter__ heredado devuelve self tras await y la subclase debe definir un __aexit__ asíncrono. Recibe tres None al terminar bien o tipo, excepción y traza. Un resultado verdadero suprime la excepción.

En el ejemplo False permite capturar ValueError fuera del bloque.

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

Ejemplos

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

Resultado

True
ValueError
caught

En el ejemplo False permite capturar ValueError fuera del bloque.

Fuentes