poros
10/4/2015 - 5:47 PM

Ignore exceptions context manager

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