Skip to content

Instantly share code, notes, and snippets.

@poros
Last active October 4, 2015 17:47
Show Gist options
  • Save poros/89a9e128214f94c61bf4 to your computer and use it in GitHub Desktop.
Save poros/89a9e128214f94c61bf4 to your computer and use it in GitHub Desktop.
Ignore exceptions context manager
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