Archive

Posts Tagged ‘ignored exception’

How to ignore an exception — the elegant way

September 7, 2013 1 comment

This idea was presented by Raymond Hettinger at PyCon US 2013. He is talking about it at 43:30: http://www.youtube.com/watch?v=OSGv2VnC0go.

Problem
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.

Design a site like this with WordPress.com
Get started