我有很多这样的代码块:
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)
我希望写一些像这样的神奇代码:
some_magic:
# varying codes here, where a and b are also available
这可能吗?
请您参考如下方法:
如果您不能或不想为a 和b 实现上下文协议(protocol),您可以使用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
