8

这个问题中,我定义了一个包含上下文管理器的上下文管理器。完成这种嵌套的最简单正确的方法是什么?最后我打电话self.temporary_file.__enter__()过去了self.__enter__()。但是,在 中self.__exit__,我很确定我必须调用self.temporary_file.__exit__(type_, value, traceback)finally 块以防引发异常。如果出现问题,我应该设置 type_、value 和 traceback 参数self.__exit__吗?我检查了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)
4

2 回答 2

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块结束时)。

于 2012-01-04T00:04:21.123 回答
4

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

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

  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)

这允许使用生成器语法声明 contextmanager 类@contextlib.contextmanager。它使嵌套 contextmanager 更加自然,无需手动调用__enter__and __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)

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

于 2020-04-28T01:46:02.863 回答