classSuppressErrors:
def__init__(self, *exceptions):
self.exceptions = exceptions
def__enter__(self):
return self
def__exit__(self, exc_type, exc_val, exc_tb):
if exc_type andissubclass(exc_type, self.exceptions):
print(f"Suppressed: {exc_type.__name__}: {exc_val}")
returnTrue# Suppress the exceptionreturnFalse# Let it propagatewith SuppressErrors(KeyError, IndexError):
d = {}
print(d["missing"]) # Suppressed!print("Continued after suppressed KeyError")
# This is what contextlib.suppress doesfrom contextlib import suppress
with suppress(FileNotFoundError):
open("nonexistent.txt")
print("Continued after suppressed FileNotFoundError")
Output
Click "Run" to execute your code
When __exit__ returns True, the exception is suppressed. This is how contextlib.suppress works internally.
Challenge
Try modifying the code above to explore different behaviors. Can you extend the example to handle a new use case?