import contextlib # Новое в версии 3.10. contextlib.AsyncContextDecorator
Функция AsyncContextDecorator()
модуля contextlib
позволяет использовать менеджер контекста в качестве декоратора.
Работает подобно ContextDecorator
, но только для асинхронных функций.
Новое в версии 3.10.
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` в качестве декоратора >>> @mycontext() ... async def function(): ... print('The bit in the middle') >>> run(function()) # Starting # The bit in the middle # Finishing # использование `mycontext` с оператором `with` >>> async def function(): ... async with mycontext(): ... print('The bit in the middle') >>> run(function()) # Starting # The bit in the middle # Finishing