Skip to content

Commit c892ee4

Browse files
author
Sachin Saharan
committed
Set sys.last_value / sys.last_exc before entering the debugger
**Background:** In commit 6eae532, we introduced a new utility in pyflyby named `saveframe`. This utility is designed to save error stack frames upon an exception. Users can also enter a debugger after an exception (using ipdb.pm()) and call `saveframe` to dump a specific frame. `saveframe` relies on `sys.last_value` (or `sys.last_exc` in Python 3.12) to retrieve the last exception object raised. These attributes are automatically set by Python after an uncaught exception occurs. **Issue:** When a user executes a script or command using `py <some_script_or_command>` or employs the `@debug_on_exception` decorator, the exception is caught, and the debugger is invoked. Consequently, `sys.last_value` (or `sys.last_exc`) is not set. If the user attempts to call `saveframe` within the debugger, it fails because the necessary exception information is unavailable. **Solution:** In this commit, we modified the code to explicitly set `sys.last_value` (or `sys.last_exc`) after an exception is caught and before entering the debugger. This ensures that users can directly enter the debugger and successfully call the `pyflyby.saveframe` function. Request: PyInf#12047
1 parent 0435043 commit c892ee4

File tree

1 file changed

+8
-0
lines changed

1 file changed

+8
-0
lines changed

lib/python/pyflyby/_dbg.py

+8
Original file line numberDiff line numberDiff line change
@@ -316,6 +316,14 @@ def _debug_exception(*exc_info, **kwargs):
316316
# will cause print_verbose_tb to include a line with just a colon.
317317
# TODO: avoid that line.
318318
exc_info = ("", "", exc_info)
319+
if exc_info[1]:
320+
# Explicitly set sys.last_value / sys.last_exc to ensure they are available
321+
# in the debugger. One use case is that this allows users to call
322+
# pyflyby.saveframe() within the debugger.
323+
if sys.version_info < (3, 12):
324+
sys.last_value = exc_info[1]
325+
else:
326+
sys.last_exc = exc_info[1]
319327

320328
with _DebuggerCtx(tty=tty) as pdb:
321329
if debugger_attached:

0 commit comments

Comments
 (0)