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.

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.

Advertisements
  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):
    os.remove(‘somefile.txt’)

    https://docs.python.org/3.5/library/contextlib.html#module-contextlib

  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: