ID EN
Contextlib

AsyncContextDecorator

Python 3.11

Similar to ContextDecorator but only for asynchronous functions.

Syntax

PYTHON
class contextlib.AsyncContextDecorator

Examples

Example 1
PYTHON
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
Example 2
PYTHON
>>> @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

See Also

ContextDecorator