如何简化这种Python代码?

时间:2016-03-09 10:02:13

标签: 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

这可能吗?

2 个答案:

答案 0 :(得分:5)

如果您不能或不想为ab实施上下文协议,则可以使用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

答案 1 :(得分:3)

ab的类实现上下文管理器协议,并使用with statement

with get_a() as a, get_b() as b:
    do_magic

现在,如果get_aget_b返回打开的文件句柄,它们将在块结束时自动关闭。如果返回的值是自定义类,则该类应具有__enter__ and __exit__ magic methods