withAdvanced Examples

Wraps a block with a context manager for automatic setup/teardown

Exception suppression in __exit__

Controlling whether exceptions propagate.

python
class SuppressErrors:
    def __init__(self, *exceptions):
        self.exceptions = exceptions

    def __enter__(self):
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        if exc_type and issubclass(exc_type, self.exceptions):
            print(f"Suppressed: {exc_type.__name__}: {exc_val}")
            return True  # Suppress the exception
        return False  # Let it propagate

with SuppressErrors(KeyError, IndexError):
    d = {}
    print(d["missing"])  # Suppressed!

print("Continued after suppressed KeyError")

# This is what contextlib.suppress does
from contextlib import suppress
with suppress(FileNotFoundError):
    open("nonexistent.txt")
print("Continued after suppressed FileNotFoundError")

When __exit__ returns True, the exception is suppressed. This is how contextlib.suppress works internally.

Want to try these examples interactively?

Open Advanced Playground