WissensdatenbankPrüfungszentrum
DEDeutsch
Sprache wählen13

CKTIS / Python

contextlib.aclosing

Umgibt ein Objekt mit aclose() durch einen async-with-Bereich.

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

Syntax

async with contextlib.aclosing(thing) as resource:

Umgibt ein Objekt mit aclose() durch einen async-with-Bereich.

Beim Eintritt kommt dasselbe Objekt zurück und beim Austritt wird aclose im selben Task und Kontext erwartet. So räumt der Generator nach break in async for noch vor dem Verlassen auf. Hier folgt auf 4 das closed aus finally.

Eine Ausnahme im Rumpf wird normalerweise weitergegeben.

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

Beispiele

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

Ergebnis

4
closed

Eine Ausnahme im Rumpf wird normalerweise weitergegeben.

Quellen