Skip to content

Instantly share code, notes, and snippets.

@sirkonst
Last active May 24, 2016 11:42
Show Gist options
  • Save sirkonst/95a6a0ba2565739c5ffd to your computer and use it in GitHub Desktop.
Save sirkonst/95a6a0ba2565739c5ffd to your computer and use it in GitHub Desktop.
Decorator skip_error
class skip_error(object):
def __init__(self, exception, fn=None, default=None):
self.exception = exception
self.fn = fn
self.default = default
def __enter__(self):
return self.default
def __exit__(self, exc_type, exc_value, traceback):
if isinstance(exc_value, self.exception):
if self.fn and not self.fn(exc_value):
return False
return True
def __call__(self, default):
self.default = default
return self
# --- examples ---
with skip_error(RuntimeError, lambda e: e.message == 'test', default=7) as a:
raise RuntimeError('test')
a = 1
print a # printed 7
skip_test2 = skip_error(RuntimeError, lambda e: e.message == 'test2')
with skip_test2(-2) as a:
raise RuntimeError('test2')
a = 2
print a # printed -2
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment