Fix mismatched traceback in pythonrc.py injection#25480
Fix mismatched traceback in pythonrc.py injection#25480CNSeniorious000 wants to merge 2 commits intomicrosoft:mainfrom
pythonrc.py injection#25480Conversation
There was a problem hiding this comment.
Pull request overview
This PR fixes a traceback mismatch issue in the Python interactive console caused by VS Code's pythonrc.py injection. When PYTHONSTARTUP points to pythonrc.py, Python exposes the module's __loader__ in the global namespace, which causes linecache to incorrectly display tracebacks pointing to pythonrc.py instead of the actual source files.
Key Changes:
- Sets
__spec__and__loader__to None inpythonrc.pyto prevent linecache from caching this file - Adds an explanatory comment documenting why these attributes are set to None
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
| if sys.platform != "win32": | ||
| import readline | ||
|
|
||
| # Avoid caching this file by linecache and incorrectly report tracebacks. |
There was a problem hiding this comment.
The comment has a grammatical error. It should say "incorrectly reporting tracebacks" instead of "incorrectly report tracebacks".
| # Avoid caching this file by linecache and incorrectly report tracebacks. | |
| # Avoid caching this file by linecache and incorrectly reporting tracebacks. |
| import readline | ||
|
|
||
| # Avoid caching this file by linecache and incorrectly report tracebacks. | ||
| __spec__ = __loader__ = None |
There was a problem hiding this comment.
The new behavior of setting __spec__ and __loader__ to None should have test coverage to ensure that these attributes are properly set and that they prevent linecache from incorrectly caching this file. Consider adding a test that verifies these attributes are None after module import.
|
Hi @CNSeniorious000! Sorry for the delay on getting around to this, two items:
|
Since vscode-python injects
PYTHONSTARTUPintopythonrc.pyto show the "Ctrl click to launch VS Code Native REPL" message, traceback always shows lines insidepythonrc.pyin the interactive console.Example:
That's because python sets
__main__to thepythonrc.pymodule, which has a__loader__attribute. The__loader__object is then exposed in the global namespace of the interactive console. However, linecache uses__loader__to get the source code, causing the mismatch.After this PR, the traceback points to the right source now:
In the
_pyrepl.__main__module, there was some comment mentioning this behavior and they set__loader__ = Noneto avoid this. See python/cpython#129098 for more information