Contextlib.suppress enhancement: an optional callback

I’d like to propose that contexlib.suppress could optionally invoke a callback with the caught exception. Sometimes we are suppressing errors just to isolate some important core functionality from minor unexpected problems. This proposal allows to take a notice of such suppressed errors to deal with them later.

    def log_problem(exc):
        ...

    for job in queue:
        process(job)
        with contextlib.suppress(OSError, handler=log_problem):
            send_notification(job.owner)

Equivalent:

    try:
        send_notification(job.owner)
    except OSError as exc:     # using the suppress() argument here
        try:
            log_problem(exc)
        except Exception:      # always ignoring all errors here
            pass

Another example:

    for file in filenames:
        with contextlib.suppress(
                FileNotFoundError, handler=count_missing_files):
            os.remove(file)
2 Likes