exception_note.py

exception_note.py (740 bytes)

from contextlib import contextmanager
import typing


@contextmanager
def exceptionNote(note: str | typing.Callable[[], str]) -> typing.Iterator[None]:
    """Add a note if an exception propagates from a 'with'-block.

    The ``note`` argument may be a string or a zero-arg callable
    (`lambda: f"note {x}"`).

    Using a lambda argument may be desirable if the note is the result
    of e.g., a formatting operation, which is deferred until an
    exception actually occurs."""
    try:
        yield
    except Exception as e:
        if not isinstance(note, str):
            note = note()
        e.add_note(note)
        raise


if __name__ == "__main__":
    with exceptionNote("while demonstrating exceptionNote"):
        3 / 0