當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


Python contextlib.AsyncContextDecorator用法及代碼示例


用法:

class contextlib.AsyncContextDecorator

類似於ContextDecorator,但僅適用於異步函數。

AsyncContextDecorator 的示例:

from asyncio import run
from contextlib import AsyncContextDecorator

class mycontext(AsyncContextDecorator):
    async def __aenter__(self):
        print('Starting')
        return self

    async def __aexit__(self, *exc):
        print('Finishing')
        return False

>>> @mycontext()
... async def function():
...     print('The bit in the middle')
...
>>> run(function())
Starting
The bit in the middle
Finishing

>>> async def function():
...    async with mycontext():
...         print('The bit in the middle')
...
>>> run(function())
Starting
The bit in the middle
Finishing

3.10 版中的新函數。

相關用法


注:本文由純淨天空篩選整理自python.org大神的英文原創作品 contextlib.AsyncContextDecorator。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。