[英]python asynchronous context manager
在 Python Lan Ref. 3.4.4,據說__aenter__()
和__aexit__()
必須返回 awaitables。 但是,在示例異步上下文管理器中,這兩個方法返回 None:
class AsyncContextManager:
async def __aenter__(self):
await log('entering context')
async def __aexit__(self, exc_type, exc, tb):
await log('exiting context')
這段代碼正確嗎?
此示例中的方法不返回None
。 它們是async
函數,會自動返回(可等待的)異步協程。 這類似於生成器函數返回生成器迭代器的方式,即使它們通常沒有return
語句。
您的__aenter__
方法必須返回一個上下文。
class MyAsyncContextManager:
async def __aenter__(self):
await log('entering context')
# maybe some setup (e.g. await self.setup())
return self
async def __aexit__(self, exc_type, exc, tb):
# maybe closing context (e.g. await self.close())
await log('exiting context')
async def do_something(self):
await log('doing something')
用法:
async with MyAsyncContextManager() as context:
await context.do_something()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.