Created
May 16, 2012 17:32
-
-
Save jtolio/2712451 to your computer and use it in GitHub Desktop.
This file contains 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 AtFuncExit(object): | |
"""Similar to Go-lang's defer keyword. Allows execution of a list of | |
functions at a block exit boundary. | |
""" | |
def __init__(self, swallow_errors=False, fifo=False): | |
self._exception_calls = [] | |
self._normal_calls = [] | |
self._swallow_errors = swallow_errors | |
self._fifo = fifo | |
def __enter__(self): | |
return self | |
def add_to_except(self, call, *args, **kwargs): | |
self._exception_calls.append((call, args, kwargs)) | |
def add(self, call, *args, **kwargs): | |
self._normal_calls.append((call, args, kwargs)) | |
def add_to_both(self, call, *args, **kwargs): | |
self._normal_calls.append((call, args, kwargs)) | |
self._exception_calls.append((call, args, kwargs)) | |
def __exit__(self, exc_type, exc_value, traceback): | |
if exc_type is None: | |
call_list = self._normal_calls | |
else: | |
call_list = self._exception_calls | |
if not self._fifo: | |
call_list = reversed(call_list) | |
for call, args, kwargs in call_list: | |
try: | |
call(*args, **kwargs) | |
except Exception, e: | |
if not self._swallow_errors: | |
raise e | |
logger.error("%s", e) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment