Skip to content

gh-122622: Add PyREPL pre_execution_hook - #157241

Open
edvilme wants to merge 5 commits into
python:mainfrom
edvilme:pyrepl-hook
Open

gh-122622: Add PyREPL pre_execution_hook#157241
edvilme wants to merge 5 commits into
python:mainfrom
edvilme:pyrepl-hook

Conversation

@edvilme

@edvilme edvilme commented Sep 9, 2026

Copy link
Copy Markdown
Contributor

Supersedes #144724

Adds custom hook to PyREPL that can be configured by tools such as VSCode

image

This pull request introduces a new pre_execution_hook mechanism to the _pyrepl interactive console, allowing external code to register a callback that is invoked before each statement is executed. Comprehensive tests are added to verify the hook's behavior, including its default state, invocation, error handling, and interaction with REPL commands.

New pre-execution hook feature:

  • Added a pre_execution_hook attribute to _pyrepl.__init__, which can be set to a callable that receives each statement before execution (Lib/_pyrepl/__init__.py).
  • Modified run_multiline_interactive_console in simple_interact.py to call the hook before executing each statement, safely ignoring exceptions raised by the hook (Lib/_pyrepl/simple_interact.py). [1] [2]

Testing and validation:

  • Added a new test class TestPreExecutionHook in test_interact.py to verify the hook is unset by default, is called with the correct statement, does not break the REPL if it raises, and is not called for REPL commands (Lib/test/test_pyrepl/test_interact.py).
  • Updated test imports to include _pyrepl and MagicMock for mocking and patching in tests (Lib/test/test_pyrepl/test_interact.py).

CC @brettcannon @anthonykim1 @pablogsal

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant