Skip to content

Instantly share code, notes, and snippets.

@yoavram
Created February 3, 2017 06:29
Show Gist options
  • Save yoavram/f8e3900d2afe408028b430c48dea4422 to your computer and use it in GitHub Desktop.
Save yoavram/f8e3900d2afe408028b430c48dea4422 to your computer and use it in GitHub Desktop.
A context manager that suppresses exceptions (like contextlib.suppress) and instead evokes warnings. Implementation idea by @alonhorev.
import contextlib
class ExceptionWarning(Warning):
pass
@contextlib.contextmanager
def warn_and_suppress(*exceptions):
try:
yield
except exceptions as e:
import warnings
warnings.warn(str(e), ExceptionWarning, stacklevel=2)
if __name__ == '__main__':
with warn_and_suppress(ZeroDivisionError):
a = 1 / 0
with warn_and_suppress(FileNotFoundError, FileExistsError):
b = 5 / 0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment