在 __enter__ 中输入上下文管理器

ben*_*n w 6 python macros contextmanager

将上下文管理器定义为函数,可以很容易地以编程方式从其中输入一个单独的(或递归的)上下文管理器,如下所示:

@contextmanager
def enter(times):
    if times:
        with enter(times - 1) as tup:
            print 'entering {}'.format(times)
            yield tup + (times,)
            print 'exiting {}'.format(times)
    else:
        yield ()
Run Code Online (Sandbox Code Playgroud)

运行这个:

In [11]: with enter(4) as x:
....:     print x
....:
entering 1
entering 2
entering 3
(1, 2, 3)
exiting 3
exiting 2
exiting 1
Run Code Online (Sandbox Code Playgroud)

所有出入境记账都为您完成,多好啊!但是如果你有一个类,而不是一个函数怎么办?

class Enter(object):
    def __init__(self, times):
        self.times = times

    def __enter__(self):
        print 'entering {}'.format(self.times)
        if self.times:
            with Enter(self.times - 1) as tup:  # WRONG
                return tup + (self.times,)
        return ()

    def __exit__(self, *_):
        print 'exiting {}'.format(self.times)
Run Code Online (Sandbox Code Playgroud)

运行此命令是错误的,因为您在运行 with 块中的任何代码之前进入和退出嵌套调用:

In [12]: with Enter(3) as tup:
    print tup
....:
entering 3
entering 2
entering 1
entering 0
exiting 0
exiting 1
exiting 2
(1, 2, 3)
exiting 3
Run Code Online (Sandbox Code Playgroud)

规定:不得强迫客户自行使用ExitStack;内部调用必须像在生成器情况下一样进行封装。涉及维护自己的私有堆栈的解决方案Enter也是次优的(在现实生活中,内部调用有必要以线程安全的方式__exit__与内部调用相匹配__enter__,但我想避免这种手动簿记,因为即使在这个简单的例子中也尽可能多。)

Jam*_*Lim 3

在其中使用嵌套上下文管理器__enter__似乎很神奇。

看一下这个:

class Enter(object):
    def __init__(self, times):
        self.times = times

    def __enter__(self):
        print('entering {}'.format(self.times))
        if self.times:
            with Enter(self.times - 1) as tup:  # WRONG
                print('returning {}'.format(tup))
                return tup + (self.times,)
        print('returning () from times={}'.format(self.times))
        return ()

    def __exit__(self, *_):
        print('exiting {}'.format(self.times))

with Enter(3) as tup:
    print(tup)
Run Code Online (Sandbox Code Playgroud)

运行此打印

entering 3
entering 2
entering 1
entering 0
returning () from times=0
returning ()
exiting 0
returning (1,)
exiting 1
returning (1, 2)
exiting 2
(1, 2, 3)
exiting 3
Run Code Online (Sandbox Code Playgroud)

我认为这在某种程度上是有道理的。心理模型可能是,当您调用 时with Enter(3) ...,必须“完成”该__enter__方法,而“完成”意味着进入和退出所有上下文管理器。

def foo():
    with Enter(2) as tup:
        return tup
# we expect Enter to exit before we return, so why would it be different when
# we rename foo to __enter__?
Run Code Online (Sandbox Code Playgroud)

让我们明确地这样做。

In [3]: %paste
class Enter(object):

    def __init__(self, times):
        self.times = times
        self._ctx = None

    def __enter__(self):
        print('entering {}'.format(self.times))
        if self.times:
            self._ctx = Enter(self.times - 1)
            tup = self._ctx.__enter__()
            return tup + (self.times,)
        else:
            return ()

    def __exit__(self, *_):
        if self._ctx is not None:
            self._ctx.__exit__()
        print('exiting {}'.format(self.times))

In [4]: with Enter(3) as tup:
   ...:     print(tup)
   ...:
entering 3
entering 2
entering 1
entering 0
(1, 2, 3)
exiting 0
exiting 1
exiting 2
exiting 3
Run Code Online (Sandbox Code Playgroud)

(在@jasonharper 的指导下回答。)