为类拥有的对象组合上下文管理器的 Pythonic 方法

标签 python contextmanager

对于某些任务,通常需要多个具有显式释放资源的对象 - 例如,两个文件;当任务是使用嵌套 with block 的函数本地时,这很容易完成,或者 - 更好的是 - 单个 with block 和多个 with_item子句:

with open('in.txt', 'r') as i, open('out.txt', 'w') as o:
    # do stuff

OTOH,当此类对象不仅是函数范围的本地对象,而是由类实例拥有时,我仍然很难理解它应该如何工作 - 换句话说,上下文管理器是如何组成的。

理想情况下,我想做这样的事情:

class Foo:
    def __init__(self, in_file_name, out_file_name):
        self.i = WITH(open(in_file_name, 'r'))
        self.o = WITH(open(out_file_name, 'w'))

并让 Foo 本身变成一个处理 io 的上下文管理器,这样当我这样做时

with Foo('in.txt', 'out.txt') as f:
    # do stuff

self.iself.o 会按照您的预期自动处理。

我修改了一些东西,例如:

class Foo:
    def __init__(self, in_file_name, out_file_name):
        self.i = open(in_file_name, 'r').__enter__()
        self.o = open(out_file_name, 'w').__enter__()

    def __enter__(self):
        return self

    def __exit__(self, *exc):
        self.i.__exit__(*exc)
        self.o.__exit__(*exc)

但是对于构造函数中发生的异常,它既冗长又不安全。找了一会,找到了this 2015 blog post ,它使用 contextlib.ExitStack 来获得与我所追求的非常相似的东西:

class Foo(contextlib.ExitStack):
    def __init__(self, in_file_name, out_file_name):
        super().__init__()
        self.in_file_name = in_file_name
        self.out_file_name = out_file_name

    def __enter__(self):
        super().__enter__()
        self.i = self.enter_context(open(self.in_file_name, 'r')
        self.o = self.enter_context(open(self.out_file_name, 'w')
        return self

这很令人满意,但我对以下事实感到困惑:

  • 我在文档中没有找到关于此用法的任何信息,因此它似乎不是解决此问题的“官方”方式;
  • 总的来说,我发现很难找到关于这个问题的信息,这让我觉得我正在尝试对这个问题应用一个非 Python 的解决方案。

一些额外的上下文:我主要在 C++ 中工作,在这个问题上, block 范围的情况和对象范围的情况没有区别,因为这个一种清理是在析构函数内部实现的(想想 __del__,但确定性地调用),析构函数(即使没有显式定义)自动调用子对象的析构函数。所以两者都是:

{
    std::ifstream i("in.txt");
    std::ofstream o("out.txt");
    // do stuff
}

struct Foo {
    std::ifstream i;
    std::ofstream o;

    Foo(const char *in_file_name, const char *out_file_name) 
        : i(in_file_name), o(out_file_name) {}
}

{
    Foo f("in.txt", "out.txt");
}

按照您通常的需要自动执行所有清理工作。

我正在寻找 Python 中的类似行为,但我再次担心我只是在尝试应用来自 C++ 的模式,而根本问题有一个我想不出的完全不同的解决方案的。


所以,总结一下:对于拥有需要清理的对象的对象成为上下文管理器本身的问题的 Pythonic 解决方案是什么,正确调用 __enter__/ __exit__ 它的 child ?

最佳答案

我认为 contextlib.ExitStack 是 Pythonic 和规范的,它是解决这个问题的合适方法。这个答案的其余部分试图展示我用来得出这个结论的链接和我的思考过程:

原始 Python 增强请求

https://bugs.python.org/issue13585

最初的想法 + 实现是作为 Python 标准库增强提出的,具有推理和示例代码。 Raymond Hettinger 和 Eric Snow 等核心开发人员对此进行了详细讨论。关于这个问题的讨论清楚地表明了最初的想法成长为适用于标准库并且是 Pythonic 的东西。尝试总结的线程是:

nikratio 最初提出:

I'd like to propose addding the CleanupManager class described in http://article.gmane.org/gmane.comp.python.ideas/12447 to the contextlib module. The idea is to add a general-purpose context manager to manage (python or non-python) resources that don't come with their own context manager

这引起了 rhettinger 的关注:

So far, there has been zero demand for this and I've not seen code like it being used in the wild. AFAICT, it is not demonstrably better than a straight-forward try/finally.

作为对此的回应,关于是否有必要进行了长时间的讨论,导致 ncoghlan 发布了这样的帖子:

TestCase.setUp() and TestCase.tearDown() were amongst the precursors to__enter__() and exit(). addCleanUp() fills exactly the same role here - and I've seen plenty of positive feedback directed towards Michael for that addition to the unittest API... ...Custom context managers are typically a bad idea in these circumstances, because they make readability worse (relying on people to understand what the context manager does). A standard library based solution, on the other hand, offers the best of both worlds: - code becomes easier to write correctly and to audit for correctness (for all the reasons with statements were added in the first place) - the idiom will eventually become familiar to all Python users... ...I can take this up on python-dev if you want, but I hope to persuade you that the desire is there...

稍后再从 ncoghlan:

My earlier descriptions here aren't really adequate - as soon as I started putting contextlib2 together, this CleanupManager idea quickly morphed into ContextStack [1], which is a far more powerful tool for manipulating context managers in a way that doesn't necessarily correspond with lexical scoping in the source code.

ExitStack 的示例/食谱/博客文章 标准库源代码本身中有几个示例和配方,您可以在添加此功能的合并修订版中看到:https://hg.python.org/cpython/rev/8ef66c73b1e1

还有一篇来自原始问题创建者 (Nikolaus Rath/nikratio) 的博文,以令人信服的方式描述了为什么 ContextStack 是一个好的模式,并提供了一些使用示例:https://www.rath.org/on-the-beauty-of-pythons-exitstack.html

关于为类拥有的对象组合上下文管理器的 Pythonic 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51649361/

相关文章:

python - 喀拉斯 ZeroDivisionError : integer division or modulo by zero

管理生成器的 Pythonic 方式

python - 如何对可变数量的文件名列表使用列表理解?

python - 基于类似于 RSpec 的嵌套上下文组织 Python unittest 测试

python - 在一系列上下文管理器上友好地使用 Python 可迭代对象

python - Python2.7 上下文管理器类中处理异常的正确方法

python - 修复处理@property setter装饰器的pyflakes

python - 使用 opencv python 识别图像中的文本数据以读取 mm/dd、描述和金额

python - 如何将多个参数传递给 Luigi 子任务?

python - 为什么从 setup.py 调用 Python 脚本会调用 Python shell?