32

在 Python 中应该如何处理在另一个上下文管理器中创建的上下文管理器?

示例:假设您有A充当​​上下文管理器的类,以及B还充当上下文管理器的类。但是类B实例必须实例化并使用类的实例A。我已经完成了 PEP 343,这是我想到的解决方案:

class A(object):
    def __enter__(self):
        # Acquire some resources here
        return self

    def __exit__(seplf, exception_type, exception, traceback):
        # Release the resources and clean up
        pass


class B(object):
    def __init__(self):
        self.a = A()

    def __enter__(self):
        # Acquire some resources, but also need to "start" our instance of A
        self.a.__enter__()
        return self

    def __exit__(self, exception_type, exception, traceback):
        # Release the resources, and make our instance of A clean up as well
        self.a.__exit__(exception_type, exception, traceback)

这是正确的方法吗?还是我错过了一些陷阱?

4

3 回答 3

12

如果您可以使用@contextlib.contextmanager装饰器,您的生活会变得更轻松:

import contextlib

@contextlib.contextmanager
def internal_cm():
    try:
        print "Entering internal_cm"
        yield None
        print "Exiting cleanly from internal_cm"
    finally:
        print "Finally internal_cm"


@contextlib.contextmanager
def external_cm():
    with internal_cm() as c:
        try:
            print "In external_cm_f", c
            yield [c]
            print "Exiting cleanly from external_cm_f", c
        finally:
            print "Finally external_cm_f", c


if "__main__" == __name__:
    with external_cm():
        print "Location A"
    print
    with external_cm():
        print "Location B"
        raise Exception("Some exception occurs!!")
于 2015-02-09T00:57:11.103 回答
9

或者,您可以像这样编写代码:

with A() as a:
    with B(a) as b:
        # your code here

您可能想尝试的另一个解决方案可能是:

class A:

    def __init__(self):
        pass

    def __enter__(self):
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        pass

class B(A):

    def __init__(self):
        super().__init__()

    def __enter__(self):
        super().__enter__()
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        super().__exit__(exc_type, exc_val, exc_tb)

在考虑您的情况的解释后,这可能是一个更好的解决方案:

class Resource:

    def __init__(self, dependency=None):
        self.dependency = dependency
        # your code here

    def __enter__(self):
        if self.dependency:
            self.dependency.__enter__()
        # your code here
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        # your code here
        if self.dependency:
            self.dependency.__exit__(exc_type, exc_val, exc_tb)

我不确定以下实现是否正确,但__exit__必须妥善处理异常。我有点难以想象如何在正确处理异常的同时递归地链接调用。

class Resource:

    def __init__(self, dependency=None):
        self.dependency = dependency
        self.my_init()

    def __enter__(self):
        if self.dependency:
            self.dependency.__enter__()
        return self.my_enter()

    def __exit__(self, exc_type, exc_val, exc_tb):
        suppress = False
        try:
            suppress = self.my_exit(exc_type, exc_val, exc_tb)
        except:
            exc_type, exc_val, exc_tb = sys.exc_info()
        if suppress:
            exc_type = exc_val = exc_tb = None
        if self.dependency:
            suppress = self.dependeny.__exit__(exc_type, exc_val, exc_tb)
            if not supress:
                raise exc_val.with_traceback(exc_tb) from None
        return suppress

    def my_init(self):
        pass

    def my_enter(self):
        pass

    def my_exit(self, exc_type, exc_val, exc_tb):
        pass
于 2014-07-08T16:43:04.620 回答
1

下面是一个在 contextmanager 中手动管理资源的例子: 外部 contextmanager 管理内部。

class Inner:

    def __enter__(self):
        print("<inner>")
        return self

    def __exit__(self, exc_type, exc_value, traceback):
        print("</inner>")


class Outer:

    def __init__(self):
        self.inner = Inner()

    def __enter__(self):
        self.inner.__enter__()
        try:
            #raise RuntimeError("Suppose we fail here")
            print("<outer>")
            return self
        except Exception as e:
            self.inner.__exit__(None, None, None)
            raise e

    def __exit__(self, exc_type, exc_value, traceback):
        print("</outer>")
        self.inner.__exit__(exc_type, exc_value, traceback)

使用正常:

with Outer() as scope:
    #raise RuntimeError("Suppose we fail here")
    pass

细心的读者会注意到,内部上下文管理器现在变成了一个毫无意义的木偶傀儡(因为我们是手动拉它的线程)。随它吧。

于 2018-06-27T08:38:28.233 回答