问题
I have many functions that exploit the context manager pattern:
@contextmanager
def f():
# Do preliminary stuff.
yield
# Do final stuff.
I use an ExitStack
to call all of these context managers.
I am considering the pattern:
@threeblock_contextmanager
def f():
# Do preliminary stuff.
yield
# Do intermediary stuff.
yield
# Do final stuff.
I've been looking at the source and thought I would modify it in some way. Is there a nice way to accomplish this? My other option is to add a method to each class that returns a context manager. The disadvantage of adding a method is that the intuitive linear view of the code is lost because the intermediary stuff will be in a different method rather than placed between the preliminary and final stuff, which I consider more logical.
As requested, more code:
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()
来源:https://stackoverflow.com/questions/24424980/how-do-i-write-a-three-block-context-manager-in-python