Skip to content

Instantly share code, notes, and snippets.

@sandbender
Last active August 29, 2015 14:05
Show Gist options
  • Save sandbender/76e8ad7767ada69cea96 to your computer and use it in GitHub Desktop.
Save sandbender/76e8ad7767ada69cea96 to your computer and use it in GitHub Desktop.
Python context manager to swallow the given exception types (or all exceptions by default)
class swallow(object):
"""
This is a context manager (use via 'with' syntax) that will
'swallow' any Exceptions of the given type within the block
being managed.
If nothing is passed to the context manager constructor, then
*any* `Exception` generated within the block will be swallowed.
The cosntructor arg is the same format as the 2nd arg of the
`issubclass(..)` builtin, ie: an Exception class or a tuple
of Exception classes.
"""
def __init__(self, exc_type=Exception):
self.exc_type = exc_type
def __enter__(self): pass
def __exit__(self, exc_type, *args):
if exc_type is not None and issubclass(exc_type, self.exc_type):
return True # Exception will be swallowed - see PEP-0343
return False
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment