如何简化这种Python代码?
我有很多这样的代码块:如何简化这种Python代码?,python,Python,我有很多这样的代码块: 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 我希望写
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
我希望写一些像这样的神奇代码:
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
类实现上下文管理器协议,并使用:
现在,如果
get_a
和get_b
返回打开的文件句柄,它们将在块的末尾自动关闭。如果返回的值属于自定义类,则该类应具有。让a
和b
类实现上下文管理器协议,并使用:
现在,如果
get_a
和get_b
返回打开的文件句柄,它们将在块的末尾自动关闭。如果返回的值是自定义类的值,则该类应具有。如果您不能或不想为a
和b
实现上下文协议,则可以使用工具创建上下文:
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
如果您不能或不想为
a
和b
实现上下文协议,则可以使用工具创建上下文:
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
为什么不把它们都合并到一个
中try
和finally
?为什么不把它们都合并到一个中try
和finally
?上选(即将在搜索引用后写入)上选(即将在搜索引用后写入)