Advertisement
DeaD_EyE

suppress

Feb 18th, 2020
344
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.85 KB | None | 0 0
  1. class suppress:
  2.     """
  3.    Suppress *exceptions in contextmanager
  4.    If subclass is True, each exception is checked,
  5.    if it's a subclass. Exception for example catch all Exceptions.
  6.    
  7.        >>> with suppress(ArithmeticError, subclass=True) as exc:
  8.        >>>     1 / 0
  9.        >>> print(exc.etype, exc.value, exc.traceback)
  10.    """
  11.     def __init__(self, *exceptions, subclass=False):
  12.         self.exceptions = set(exceptions)
  13.         self.subclass = subclass
  14.     def __enter__(self):
  15.         return self
  16.     def __exit__(self, etype, val, tb):
  17.         self.etype = etype
  18.         self.value = val
  19.         self.traceback = tb
  20.        
  21.         if self.subclass:
  22.             return any(
  23.                 issubclass(etype, exc)
  24.                 for exc in self.exceptions
  25.             )
  26.         else:
  27.             return etype in self.exceptions
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement