Skip to Content
Course content

320: Suppressing Exceptions with contextlib.suppress

Click on the "Edit" button in the top corner of the screen to edit your slide content.

A few years ago, I was reviewing a cleanup script written by a developer who was clearly trying to be thorough. They were deleting a series of temporary cache files before starting a fresh build process. Every single os.remove() call was wrapped in a four-line try...except FileNotFoundError: pass block. It wasn't "wrong"—it worked perfectly—but the actual logic of the script was buried under a mountain of boilerplate. It felt like reading a book where every third sentence was "I am now turning the page."

When you find yourself writing an exception handler that does absolutely nothing other than ignore the error, you're creating visual noise. Python gives us a much more elegant way to handle this using contextlib.suppress.

Cleaning Up the 'Try-Except-Pass' Noise

Usually, we're taught that pass is the way to ignore an error. But when you have five or six different operations that might fail in a way you don't care about, your code starts to look like a series of indentations rather than a clean flow. contextlib.suppress is a context manager designed specifically for those moments where an exception is expected and intentionally ignored.

from contextlib import suppress
import os

# The old, noisy way
try:
    os.remove("old_log.txt")
except FileNotFoundError:
    pass

# The clean, professional way
with suppress(FileNotFoundError):
    os.remove("old_log.txt")

The with suppress(...) block tells Python: "If this specific error happens inside this block, just keep moving." It's essentially a shorthand for that try...except...pass pattern, but it expresses your intent much more clearly to whoever is reading your code later.

Handling Multiple Exception Types

Sometimes, a single operation could fail for a couple of different reasons, and you're fine with either. For instance, you might be trying to close a network socket that might have already been closed or might not even have been initialized. You can pass multiple exception classes into suppress as arguments.

from contextlib import suppress

with suppress(TypeError, ValueError):
    # Imagine some volatile data conversion here
    result = int(some_weird_input)

I like this because it keeps the "happy path" of your code aligned to the left margin. You aren't jumping back and forth across indentation levels just to say, "Yeah, this might fail; ignore it."

The Danger of Silent Failures

Now, a word of caution. Just because you can suppress exceptions doesn't mean you should do it blindly. The biggest mistake I see developers make is suppressing a base class like Exception. Never do that. If you suppress Exception, you'll miss KeyboardInterrupt, MemoryError, or—more likely—a NameError because you misspelled a variable name inside the block.

Only suppress the most specific exception possible. If you're expecting a FileNotFoundError, suppress exactly that. If you suppress everything, you're essentially turning off the smoke alarm in your house because you're cooking toast; eventually, you'll miss an actual fire.




📋 Practical Task

Exercise: Silencing Directory Creation Errors in a Setup Script

You are writing a setup script that ensures a specific folder structure exists for an application. You need to create a directory named "app_data". However, if the directory already exists, Python will raise a FileExistsError. Instead of checking if the directory exists first (which can lead to race conditions) or using a bulky try/except block, use contextlib.suppress to handle this.

Requirements:

  • Import os and suppress from contextlib.
  • Use a with suppress(...) block to attempt to create a directory named "app_data" using os.mkdir().
  • Ensure that if the directory already exists, the program continues to run without printing an error or crashing.
  • Add a print statement after the block saying "Setup complete!" to verify the script finished.
Rating
0 0

There are no comments for now.

to be the first to leave a comment.