Last active
October 4, 2015 17:47
-
-
Save poros/89a9e128214f94c61bf4 to your computer and use it in GitHub Desktop.
Ignore exceptions context manager
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
try: | |
os.remove('somefile.tmp') | |
except OSError: | |
pass | |
# note: checking if the file exists before deletion leads to a race condition | |
# PYTHON 3 | |
from contextlib import suppress | |
with suppress(OSError): | |
os.remove('somefile.tmp') | |
# PYTHON 2 | |
from contextlib import contextmanager | |
@contextmanager | |
def suppress(*exceptions): | |
try: | |
yield | |
except exceptions: | |
pass |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment