DEV Community

Cover image for Python tips: elegant exception handling with contextlib.suppress
Vitaly Shchurov
Vitaly Shchurov

Posted on • Edited on

Python tips: elegant exception handling with contextlib.suppress

Python has a very elegant and concise way of handling exceptions, to my taste. What's more exciting is that it also has other techniques to make your code even more readable. Today, I'm going to share a small tip on using a context manager for handling 'lazy exceptions.'

Imagine that you need to handle a couple of possible errors and tell your program to ignore them. You can do it ‘the long way’ using the good old try except syntax:

try:
    do_a()
    try:
        do_b()
    except ExceptionB:
        pass
except ExceptionA:
    pass
Enter fullscreen mode Exit fullscreen mode

Looks rather incomprehensible and ugly, not to mention the case when you've got several such exceptions to handle. Following the Python principles 'Flat is better than nested' nad 'Simple is better than complex', we can break it down:

try:
    do_a()
except ExceptionA:
    pass

try:
    do_b()
except ExceptionB:
    pass
Enter fullscreen mode Exit fullscreen mode

A bit easier to read, but still, quite long for a simple 'try to do a() and b(), and if you fail, just keep going'. Here's where the contextlib module from the Python standard library comes to our rescue. contextlib provides utilities for common tasks involving the with statement, and, in our case, can help our code to achieve better clarity:

from contextlib import suppress
with suppress(ExceptionA):
    do_a()
    with suppress(ExceptionB):
        do_b()
Enter fullscreen mode Exit fullscreen mode

A bit abstract, though. Python documentation gives us a more practical example. Say, we want to remove a file in case it still exists on our system. If we do it the usual way, we’ll type:

try:
    os.remove('somefile.tmp')
except FileNotFoundError:
    pass
Enter fullscreen mode Exit fullscreen mode

With suppressing, it’ll be like:

from contextlib import suppress

with suppress(FileNotFoundError):  # if you get this exception
    os.remove('somefile.tmp')  # while trying to do this, go on
Enter fullscreen mode Exit fullscreen mode

Two lines instead of four (well, not counting the import line). Not bad, especially if you have several such exceptions to handle.

There's a limitation to using this method, though. Use it only with specific exceptions to cover those errors where you know it's okay to keep going (pass). If you need to give specific instructions what to do if something goes wrong, than the traiditional try except will fit you better.

Hope you enjoyed my post! If you did, don't forget to like it. Thank you :)

Top comments (0)