◐ Shell
clean mode source ↗

gh-102778: IDLE - make sys.last_exc available in Shell after traceback by iritkatriel · Pull Request #103314 · python/cpython

Yes and no. The 'yes' part is that "Running user code" says that IDLE generally tries to run user code so that it gives the same output (objects) one would get if one runs the same code in python itself, in either batch or interactive mode. Some known differences are then listed in this section and the next, "Displaying output in Shell".

For this issue, user-code sys.last_xyz expressions should have the same result as with python.exe in the same circumstances. In user code, sys.last_exc must continue raising an attribute error in 3.11 like it does in REPL. I considered whether to use last_exc 'internally' in 3.11, but decided to leave 3.11 alone. (And you never suggested touching it.)

In 3.12, last_exc must be set after the the first uncaught-by-user-code 'interactive' exception. Since IDLE intends to simulate running code from an editor with python -i, all user exceptions caught by IDLE are treated as interactive. Hence the two new lines in run.py that unconditionally set last_exc along with the deprecated but still supported attributes. For users, these 2 lines are the only new code relevant to 'Support sys.last_exc in IDLE'. They should have been in the last alpha and should be added, I think, now.

The immediate manual test is that IDLE imitate the REPL as below instead of raising AttributeError as it does now.

>>>import sys; 1/0
Traceback ...
>>> sys.last_exc
ZeroDivisionError('division by zero')

Fixing test_run to check this may or may not be simple.

This change should get a line in What's New 3.12. Check the IDLE entry in What's New 3.11. This could be done later.

The no part is that the rest of the patch, including that to pyshell.py, only concerns stackviewer. This is internal code of no direct concern to users. It need not be done now, or even in 3.12, as it should continue to work. When revised, the support for 2.x string exceptions and the use of the old attributes (which were for support of string exceptions) should be removed. The only effect on users would be that the way to disable stackviewer will change from del sys.last_traceback (undocumented except the the error message ;-) to del sys.last_exc. So revert the current stackview changes and draft a separate PR or wait for me to do so in maybe a week.