如何在Python中编写三块上下文管理器?

时间:2014-06-26 07:42:20

标签: python contextmanager

我有许多利用上下文管理器模式的函数:

@contextmanager
def f():
    # Do preliminary stuff.
    yield
    # Do final stuff.

我使用ExitStack来调用所有这些上下文管理器。

我正在考虑这种模式:

@threeblock_contextmanager
def f():
    # Do preliminary stuff.
    yield
    # Do intermediary stuff.
    yield
    # Do final stuff.

我一直在看the source并认为我会以某种方式修改它。有没有一个很好的方法来实现这一目标?我的另一个选择是为每个返回上下文管理器的类添加一个方法。添加方法的缺点是代码的直观线性视图丢失了,因为中间的东西将采用不同的方法,而不是放在初级和最终的东西之间,我认为这更合乎逻辑。


根据要求,更多代码:

def fire(self, cluster_index, obs_count=1.0):
    with ExitStack() as stack:
        for link in self.terminal.out:
            stack.enter_context(
                link.source_firing(cluster_index, obs_count))
        for link in self.terminal.in_:
            stack.enter_context(
                link.target_firing(cluster_index, obs_count))

        # At this point all context managers have been run up until
        # their yield.   They saw a signal that was neither updated at
        # the source nor the target.

        # Update signals.

        # TODO: at this point, the context managers need to send any signals they
        # want to send and yield again.

    # At this point all context managers have been run entirely.
    # On closing, they saw a signal has been updated at both the source
    # and the receiver.

    self.ask_for_reschedule()

0 个答案:

没有答案