CKTIS / Python
contextlib.asynccontextmanager
Pretvara funkciju asinkronog generatora u tvornicu za async with.
Verzija: Python 3.14; repository image, production runtime not attested
Sintaksa
@contextlib.asynccontextmanagerPretvara funkciju asinkronog generatora u tvornicu za async with.
Svaki primjerak upravitelja iz generatora služi jednoj uporabi, ali kao dekorator stvara nov generator pri svakom pozivu dekorirane funkcije. Dekoriranje asinkronih funkcija dostupno je od 3.10. Točno jedan yield daje vrijednost za as, a finally može čekati čišćenje. Iznimka tijela vraća se u generator na mjestu yield i nakon hvatanja treba je ponovno izazvati za širenje.
Primjer daje 8 i na izlazu ispisuje closed.
import asyncio
async def main():
from contextlib import asynccontextmanager
events = []
@asynccontextmanager
async def cm():
try:
yield 4
finally:
await asyncio.sleep(0)
events.append("closed")
try:
async with cm() as value:
assert value == 4
raise ValueError
except ValueError:
assert events == ["closed"]
asyncio.run(main())
import asyncio
async def main():
from contextlib import asynccontextmanager
seen = []
@asynccontextmanager
async def track():
seen.append("in")
yield
@track()
async def work():
return 3
assert await work() == await work() == 3 and len(seen) == 2
asyncio.run(main())
Primjeri
import contextlib
import asyncio
@contextlib.asynccontextmanager
async def scope():
try:
yield 8
finally:
print("closed")
async def main():
async with scope() as item:
print(item)
asyncio.run(main())
Rezultat
8 closed
Primjer daje 8 i na izlazu ispisuje closed.