DEV Community

smac89
smac89

Posted on

Better way to try...except...pass in Python

The typical 'try, exception, ignore' pattern I see people using in python is this:

try:
  # do something that might raise
except (MyError1, MyError2, etc) as err:
  pass
Enter fullscreen mode Exit fullscreen mode

If you've ever found yourself doing something like that, I'm not here to tell you to stop, instead I'll show you a better way.

Introducing contextlib.suppress builtin

Using suppress, we can transform the above syntax to this:
requires python 3.4+

from contextlib import suppress
with suppress(MyError1, MyError2, etc):
  # do something that might raise
Enter fullscreen mode Exit fullscreen mode

And there we have it, from 4 lines to a nicely condensed 2 lines.

Advantages

What do you gain from this? Shorter, concise code which makes clear the intentions of the user to ignore the exceptions.

Disadvantages

The exception will never be visible outside of the context, therefore if you are being a good log keeper and in the habit of using logger.exception("I tried to do something"), the exception will not be shown by the logger.

Conclusion

If you are already using this pattern, then I'm assuming you know what you're doing. The disadvantage mentioned might be a blocker for some. Consult your nearest python guru if you experience any adverse effects.

Top comments (0)