Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Python

contextlib.AbstractAsyncContextManager

Provides an asynchronous context-manager base with a default entry method returning the manager itself.

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

Syntax

class Scope(contextlib.AbstractAsyncContextManager): ...

Provides an asynchronous context-manager base with a default entry method returning the manager itself.

A concrete subclass must implement asynchronous exit. Returning false propagates an exception from the body.

Derive an asynchronous scope and implement the abstract async __aexit__. The inherited async __aenter__ returns self. Exit receives the exception type, value and traceback, or three None values on success. Its truthy result suppresses an exception; returning False in the example lets ValueError reach the handler after the type is printed.

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

Examples

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

Result

True
ValueError
caught

Derive an asynchronous scope and implement the abstract async `__aexit__`. The inherited async `__aenter__` returns self. Exit receives the exception type, value and traceback, or three None values on success. Its truthy result suppresses an exception; returning False in the example lets ValueError reach the handler after the type is printed.

Sources