我有很多这样的代码块:
try:
a = get_a()
try:
b = get_b()
# varying codes here, where a and b are used
finally:
if b:
cleanup(b)
finally:
if a:
cleanup(a)
Run Code Online (Sandbox Code Playgroud)
我希望写一些像这样的魔术代码:
some_magic:
# varying codes here, where a and b are also available
Run Code Online (Sandbox Code Playgroud)
这可能吗?
如果您不能或不想为a和实现上下文协议b,则可以使用contextlib工具创建上下文:
from contextlib import contextmanager
@contextmanager
def managed(a):
try:
yield a
finally:
if a:
cleanup(a)
with managed(get_a()) as a, managed(get_b()) as b:
# do something here
pass
Run Code Online (Sandbox Code Playgroud)