Baza znanjaCentar za ispite
HRHrvatski
Odaberi jezik13

CKTIS / Python

contextlib.AbstractAsyncContextManager

Olakšava implementaciju naredbe async with.

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

Sintaksa

class Scope(contextlib.AbstractAsyncContextManager): ...

Olakšava implementaciju naredbe async with.

Naslijeđeni __aenter__ nakon await vraća self, a potklasa mora definirati asinkroni __aexit__. Pri uspjehu dobiva tri None, inače tip, iznimku i trag poziva. Istinit rezultat potiskuje iznimku.

U primjeru False dopušta hvatanje ValueError izvan bloka.

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

Primjeri

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

Rezultat

True
ValueError
caught

U primjeru False dopušta hvatanje ValueError izvan bloka.

Izvori