Home > python > How to ignore an exception — the elegant way

How to ignore an exception — the elegant way

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.

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.

except OSError:

That is, if the exception occurs, we do nothing.

Solution 2: the elegant way

with ignored(OSError):

Its source code in Python 2.7:

from contextlib import contextmanager

def ignored(*exceptions):
    except exceptions:

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.

  1. July 7, 2016 at 18:36

    Hey, I tried it out, but looks like this is renamed to “suppress” (; so:

    from contextlib import suppress

    with suppress(OSError):


  1. No trackbacks yet.

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: