Last active
May 24, 2016 11:42
-
-
Save sirkonst/95a6a0ba2565739c5ffd to your computer and use it in GitHub Desktop.
Decorator skip_error
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 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
Like https://docs.python.org/3/library/contextlib.html?highlight=suppress#contextlib.suppress