Created
February 3, 2017 06:29
-
-
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.
This file contains hidden or 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
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