2

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

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

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

我正在考虑这种模式:

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

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


根据要求,更多代码:

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()
4

0 回答 0