Skip to content

Instantly share code, notes, and snippets.

@xylcbd
Last active October 15, 2020 13:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save xylcbd/1b3427a5a411255bd227dcb2ed7ca138 to your computer and use it in GitHub Desktop.
Save xylcbd/1b3427a5a411255bd227dcb2ed7ca138 to your computer and use it in GitHub Desktop.
class ScopeExit:
def __init__(self, revert_exec=False):
self.revert_exec = revert_exec
self.cbs = []
def add_cb(self, cb):
self.cbs.append(cb)
def del_cb(self, cb):
used = 0
for cbx in self.cbs:
if cb == cbx:
continue
self.cbs[used] = cbx
used += 1
self.cbs = self.cbs[:used]
def __enter__(self):
pass
def __exit__(self, type, value, traceback):
if self.revert_exec:
self.cbs.reverse()
for cb in self.cbs:
cb()
def demo():
tool = ScopeExit(True)
cb1 = lambda: print('step1 exec')
cb2 = lambda: print('step2 exec')
tool.add_cb(cb1)
tool.add_cb(cb2)
tool.del_cb(cb1)
with tool:
print("begin")
return
print("end")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment