嵌套Python上下文管理器

时间:2012-01-03 23:34:41

标签: python contextmanager

this question中,我定义了一个包含上下文管理器的上下文管理器。完成此嵌套最简单的正确方法是什么?我最后在self.temporary_file.__enter__()中致电self.__enter__()。但是,在self.__exit__中,我很确定如果引发异常,我必须在finally块中调用self.temporary_file.__exit__(type_, value, traceback)。如果self.__exit__出现问题,我应该设置type_,value和traceback参数吗?我检查了contextlib,但找不到任何实用工具来帮助解决这个问题。

来自问题的原始代码:

import itertools as it
import tempfile

class WriteOnChangeFile:
    def __init__(self, filename):
        self.filename = filename

    def __enter__(self):
        self.temporary_file = tempfile.TemporaryFile('r+')
        self.f = self.temporary_file.__enter__()
        return self.f

    def __exit__(self, type_, value, traceback):
        try:
            try:
                with open(self.filename, 'r') as real_f:
                    self.f.seek(0)
                    overwrite = any(
                        l != real_l
                        for l, real_l in it.zip_longest(self.f, real_f))
            except IOError:
                overwrite = True
            if overwrite:
                with open(self.filename, 'w') as real_f:
                    self.f.seek(0)
                    for l in self.f:
                        real_f.write(l)
        finally:
            self.temporary_file.__exit__(type_, value, traceback)

2 个答案:

答案 0 :(得分:10)

创建上下文管理器的简便方法是使用contextlib.contextmanager。像这样:

@contextlib.contextmanager
def write_on_change_file(filename):
    with tempfile.TemporaryFile('r+') as temporary_file:
        yield temporary_file
        try:
             ... some saving logic that you had in __exit__ ...

然后使用with write_on_change_file(...) as f: with语句的正文将“代替”yield执行。如果您想捕获身体中发生的任何异常,请将yield自身包裹在try块中。

临时文件将始终正确关闭(当with块结束时)。

答案 1 :(得分:0)

contextlib.contextmanager非常适合函数使用,但是当我需要一个类作为上下文管理器时,我正在使用以下实用程序:

class ContextManager(metaclass=abc.ABCMeta):
  """Class which can be used as `contextmanager`."""

  def __init__(self, filename):
    self.filename = filename

  def __init__(self):
    self.__cm = None

  @abc.abstractmethod
  @contextlib.contextmanager
  def contextmanager(self):
    raise NotImplementedError('Abstract method')

  def __enter__(self):
    self.__cm = self.contextmanager()
    return self.__cm.__enter__()

  def __exit__(self, exc_type, exc_value, traceback):
    return self.__cm.__exit__(exc_type, exc_value, traceback)

这允许使用@contextlib.contextmanager中的生成器语法声明contextmanager类。嵌套contextmanager变得更加自然,而不必手动调用__enter____exit__。示例:

class MyClass(ContextManager):

  def __init__(self, filename):
    self._filename = filename

  @contextlib.contextmanager
  def contextmanager(self):
    with tempfile.TemporaryFile() as temp_file:
      yield temp_file
      ...  # Post-processing you previously had in __exit__


with MyClass('filename') as x:
  print(x)

我希望这是在标准库中...