该PEP 492提到:
async with EXPR as VAR:
BLOCK
在语义上等效于:
mgr = (EXPR)
aexit = type(mgr).__aexit__
aenter = type(mgr).__aenter__
VAR = await aenter(mgr)
try:
BLOCK
except:
if not await aexit(mgr, *sys.exc_info()):
raise
else:
await aexit(mgr, None, None, None)
但是,VAR = await aenter(mgr)
它不在try
块中,因此我想知道是否__aenter__()
允许失败。
例如,在以下aiohttp
代码片段中(摘自《入门指南》):
import aiohttp
import asyncio
async def main():
async with aiohttp.ClientSession() as session:
async with session.get('http://python.org') as response:
print("Status:", response.status)
print("Content-type:", response.headers['content-type'])
html = await response.text()
print("Body:", html[:15], "...")
loop = asyncio.get_event_loop()
loop.run_until_complete(main())
session.get('http://python.org')
可能会失败,__aexit__()
并且不会被调用以关闭上下文。
如果__aenter__
失败,__aexit__
的确是无法运行。__aenter__
在这种情况下,必须进行任何必要的清理。
__aenter__
有更多关于如何初始化以及成功初始化或未成功初始化的内容的信息,因此__aenter__
处理该对象比__aexit__
处理清理任意部分输入的上下文管理器状态要方便得多。
(对于普通的非异步上下文管理器,这是完全相同的。)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句