-
Section 1: Getting Started
-
Section 2: Core Syntax and Data Types
-
Section 3: Collections
-
39: Set Operations: Union, Intersection, Difference
-
Section 4: Control Flow
-
Section 5: Functions
-
Section 6: Turtle Graphics and Early Practice Projects
-
Section 7: Working with Files and I/O
-
Section 8: Regular Expressions
-
Section 9: Object-Oriented Python
-
Section 10: Error Handling
-
Section 11: Modules and Packages
-
Section 12: Iterators, Generators, and Functional Tools
-
Section 13: Decorators and Metaprogramming
-
Section 14: Concurrency and Parallelism
-
Section 15: Working with Dates, Times, and Numbers
-
Section 16: Standard Library Deep Dive I: Data Structures
-
Section 17: Standard Library Deep Dive II: System and Introspection
-
Section 18: Standard Library Deep Dive III: Security and Encoding
-
Section 19: Standard Library Deep Dive IV: Text and Data Utilities
-
Section 20: Networking and Web Basics
-
Section 21: Working with Databases
-
Section 22: Testing and Quality
-
Section 23: Advanced Typing
-
Section 24: Context Managers and Resource Handling
-
Section 25: Text, Unicode, and Binary Data
-
Section 26: More Functional and Iteration Tools
-
Section 27: Data Validation and Configuration
-
Section 28: Working with Images and Media
-
Section 29: Property-Based and Documentation Testing
-
Section 30: Packaging and Deployment
-
Section 31: Performance and Internals
-
Section 32: Design Patterns in Python
-
Section 33: GUI Programming
-
Section 34: Security Basics
-
Section 35: Data Structures and Algorithms
-
Section 36: Practical Projects
-
Section 37: Capstone Projects
-
Section 38: Interview and Algorithm Practice
-
Section 39: Writing Idiomatic Python
320: Suppressing Exceptions with contextlib.suppress
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
osandsuppressfromcontextlib. - Use a
with suppress(...)block to attempt to create a directory named"app_data"usingos.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.
There are no comments for now.