考慮下面的代碼:壓扁`with`和`嘗試/ finally`在Python
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())
...
或者,或者,有沒有辦法在退出範圍時可靠地執行任意代碼?
['with'語句](https://docs.python.org/3/reference/compound_stmts.html#with)可以有許多成員。我不確定您是否可以在聲明中使用任何結果變量。 – Kendas
@Kendas,雖然可以在單個'with'語句中包含多個子句,但是無法使用'with'(或不存在的'scope_exit')執行任何代碼是不可能的 – toriningen