Znalostná bázaCentrum skúšok
SKSlovenčina
Vybrať jazyk13

CKTIS / Python

contextlib.aclosing

Obalí objekt s metódou aclose() rozsahom async with.

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

Syntax

async with contextlib.aclosing(thing) as resource:

Obalí objekt s metódou aclose() rozsahom async with.

Vstup vráti ten istý objekt a výstup čaká na aclose v rovnakej úlohe a kontexte. Preto break v async for uprace generátor ešte pred ukončením rozsahu. V príklade nasleduje po 4 správa closed z finally.

Výnimka tela sa zvyčajne šíri ďalej.

import asyncio
async def main():
    from contextlib import aclosing
    seen = []
    async def stream():
        try:
            yield 1
            yield 2
        finally:
            seen.append(asyncio.current_task())
    async with aclosing(stream()) as it:
        async for value in it:
            break
    assert seen == [asyncio.current_task()]
asyncio.run(main())

Príklady

import contextlib
import asyncio

async def items():
    try:
        yield 4
        yield 9
    finally:
        print("closed")

async def main():
    async with contextlib.aclosing(items()) as it:
        async for item in it:
            print(item)
            break

asyncio.run(main())

Výsledok

4
closed

Výnimka tela sa zvyčajne šíri ďalej.

Zdroje