Skip to content

Instantly share code, notes, and snippets.

@jtolio
Created May 16, 2012 17:32
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 jtolio/2712451 to your computer and use it in GitHub Desktop.
Save jtolio/2712451 to your computer and use it in GitHub Desktop.
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