CKTIS / Python
contextlib.asynccontextmanager
Prevedie funkciu asynchrónneho generátora na továreň pre async with.
Verzia: Python 3.14; repository image, production runtime not attested
Syntax
@contextlib.asynccontextmanagerPrevedie funkciu asynchrónneho generátora na továreň pre async with.
Jedna inštancia správcu z generátora je jednorazová, ale pri použití ako dekorátor vznikne pri každom volaní dekorovanej funkcie nový generátor. Dekorovanie asynchrónnych funkcií je dostupné od 3.10. Práve jedno yield dodá hodnotu pre as a finally môže čakať na upratanie. Výnimka tela sa vloží do generátora v mieste yield a po zachytení ju pre ďalšie šírenie znova vyvolajte.
Príklad poskytne 8 a pri odchode vypíše 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())
Príklady
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())
Výsledok
8 closed
Príklad poskytne 8 a pri odchode vypíše closed.