Mixinig async context manager and straight await in asyncio
You can return __aenter__
's __await__
from your class's __await__
:
# vim: tabstop=4 expandtab
import asyncio
class Test(object):
async def __aenter__(self):
print("enter")
async def __aexit__(self, *args):
print("exit")
def __await__(self):
return self.__aenter__().__await__()
async def run():
async with Test():
print("hello")
await Test()
loop = asyncio.get_event_loop()
loop.run_until_complete(run())
loop.close()
Output:
enter
hello
exit
enter