【发布时间】:2017-05-30 09:29:39
【问题描述】:
考虑以下代码:
async with app:
...
async with app.resource as rsrc:
...
async with rsrc.foo as bar:
...
大量嵌套的with 或async with 语句会对代码的可读性产生负面影响,尤其是在测试中,同一个子句可能会被重复使用很多次。
在像 D 这样的语言中,有 scope(exit) ... 构造,它允许您将代码附加到作用域终结器列表中——一旦离开作用域,这段代码就会被执行,让您可以有效地执行 __exit__ 所做的事情,但没有添加缩进。
有没有办法在 Python 中展平 with 并执行类似的操作?
await async_with(app)
scope_exit(app.quit)
...
rsrc = await async_with(app.resource)
scope_exit(rsrc.release)
...
bar = await async_with(rsrc.foo)
scope_exit(lambda: bar.unfrob())
...
或者,有没有办法在退出范围时可靠地执行任意代码?
【问题讨论】:
-
withstatement 可以有多个成员。我不确定您是否可以在语句中使用任何结果变量。 -
@Kendas,虽然可以在单个
with语句中包含多个子句,但如果不诉诸with(或不存在的scope_exit),就不可能在两者之间执行任何代码跨度>
标签: python python-3.x