当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


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。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。