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: do_a() try: do_b() except ExceptionB: pass except ExceptionA: pass
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
A bit easier to read, but still, quite long for a simple 'try to do
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()
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
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
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
except will fit you better.
Hope you enjoyed my post! If you did, don't forget to like it. Thank you :)