如何搭配
async with api.open() as o:
...
和
o = await api.open()
在一个功能?
因为第一个require对象带有__aenter__
和__aexit__
,但是第二个require对象__await__
应该是不带的生成器await
。
我的尝试是:
def AsyncContext(aenter, aexit):
class AsyncContextClass:
async def __aenter__(self):
return await aenter()
async def __aexit__(self, *args):
return await aexit(*args)
def __await__(self):
return (yield from aenter())
return AsyncContextClass()
但是,__await__
如果aenter
用async def
(TypeError: cannot 'yield from' a coroutine object in a non-coroutine generator
)定义,它将失败。
可以与的@asyncio.coroutine
装饰器配合使用aenter
,但这很“脏”。
你可以返回__aenter__
的__await__
从你的类__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()
输出:
enter
hello
exit
enter
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句