Last active
October 15, 2020 13:14
-
-
Save xylcbd/1b3427a5a411255bd227dcb2ed7ca138 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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