How to ignore an exception — the elegant way
You want to ignore an exception.
Solution 1: the classical way
Say you want to delete a file but it’s not sure it exists.
try: os.unlink('somefile.txt') except OSError: pass
That is, if the exception occurs, we do nothing.
Solution 2: the elegant way
with ignored(OSError): os.unlink('somefile.txt')
Its source code in Python 2.7:
from contextlib import contextmanager @contextmanager def ignored(*exceptions): try: yield except exceptions: pass
This is part of Python 3.4, thus in Python 3.4 all you need is this line:
from contextlib import ignored
See the docs here.