💡 Python QuickBits — 🎭 Hidden Power of contextlib


Description:

Python’s contextlib helps you write clean, reliable resource-handling code. Beyond with open(...), you can suppress exceptions, redirect output, and build your own context managers with just a few lines — all from the standard library.


Suppress Exceptions (When You Expect Them):

Use suppress to intentionally ignore specific, known exceptions without noisy try/except blocks.

import contextlib

with contextlib.suppress(FileNotFoundError):   # ignore only this error
    with open("missing.txt") as f:             # will raise if not found…
        _ = f.read()                           # …but gets suppressed here

print("Continuing execution after suppressing FileNotFoundError...")

Redirect Output (Capture Prints):

Temporarily redirect stdout or stderr to a file or buffer — great for logs or tests.

import contextlib

with open("log.txt", "w") as f:                # destination for prints
    with contextlib.redirect_stdout(f):        # capture all prints inside
        print("This goes to log.txt, not the console")

print("Back to normal stdout")

Build Custom Context Managers:

Turn setup/teardown patterns into a neat with block using @contextmanager.

import contextlib

@contextlib.contextmanager
def managed_resource(name: str):
    print(f"[SETUP] Opening resource {name}")   # setup
    try:
        yield                                   # body of the with-block runs here
    finally:
        print(f"[CLEANUP] Closing resource {name}")  # guaranteed cleanup

with managed_resource("DB Connection"):
    print("...using the resource safely...")

Key Points:

  • suppress for expected, ignorable exceptions (be precise!).
  • redirect_stdout/redirect_stderr for capturing output.
  • @contextmanager for elegant setup → yield → teardown.
  • All standard library — no dependencies.

Code Snippet:

import contextlib    # tools for advanced context manager patterns
import sys           # used to demonstrate stdout redirection


with contextlib.suppress(FileNotFoundError):   # ignore FileNotFoundError
    with open("../sample_outputs/missing.txt") as f:             # attempt to open a non-existing file
        data = f.read()                        # no traceback raised!
print("Continuing execution after suppressing error...")


with open("../sample_outputs/log.txt", "w") as f:                       # open file for writing
    with contextlib.redirect_stdout(f):               # redirect all prints into file
        print("This will go inside log.txt")          # not shown in console
print("Back to normal stdout")


@contextlib.contextmanager
def managed_resource(name: str):
    print(f"[SETUP] Opening resource {name}")   # setup
    yield                                      # code inside `with` runs here
    print(f"[CLEANUP] Closing resource {name}") # cleanup

with managed_resource("DB Connection"):
    print("...using the resource safely...")

Link copied!

Comments

Add Your Comment

Comment Added!