Base de conhecimentoCentro de Exames
PT · PTPortuguês (Portugal)
Escolher idioma13

CKTIS / Python

contextlib.AbstractAsyncContextManager

Facilita a implementação de async with.

Versão: Python 3.14; repository image, production runtime not attested

Sintaxe

class Scope(contextlib.AbstractAsyncContextManager): ...

Facilita a implementação de async with.

O __aenter__ herdado devolve self após await e a subclasse tem de definir um __aexit__ assíncrono. Recebe três None no sucesso ou tipo, exceção e rastreio. Um resultado verdadeiro suprime a exceção.

No exemplo False permite capturar ValueError fora do bloco.

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

Exemplos

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

No exemplo False permite capturar ValueError fora do bloco.

Fontes