Uh oh!
There was an error while loading.Please reload this page.
- Notifications
You must be signed in to change notification settings - Fork33.7k
gh-83151: Make closure work on pdb#111094
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to ourterms of service andprivacy statement. We’ll occasionally send you account related emails.
Already on GitHub?Sign in to your account
Merged
Uh oh!
There was an error while loading.Please reload this page.
Merged
Changes fromall commits
Commits
Show all changes
13 commits Select commitHold shift + click to select a range
720a584 Make closure work on pdb
gaogaotiantian8232457 Always update local variables
gaogaotiantian8df6d2b 📜🤖 Added by blurb_it.
blurb-it[bot]9c68aef Merge branch 'main' into pdb-closure
gaogaotiantianfe5a6f6 Update the code for pep 667
gaogaotiantiancc21873 Remove blank line
gaogaotiantiand37b5a7 Merge branch 'main' into pdb-closure
gaogaotiantiancd46a05 Update 2023-10-20-03-50-17.gh-issue-83151.bcsD40.rst
gaogaotiantiand04bc5d Merge branch 'main' into pdb-closure
gaogaotiantianaa91238 Fix test for breakpoint change
gaogaotiantian7650aa9 Apply suggestions from code review
gaogaotiantian3c44f88 Fix some typos in review and add exception check
gaogaotiantian18e7a16 Apply suggestions from code review
gaogaotiantianFile filter
Filter by extension
Conversations
Failed to load comments.
Loading
Uh oh!
There was an error while loading.Please reload this page.
Jump to
Jump to file
Failed to load files.
Loading
Uh oh!
There was an error while loading.Please reload this page.
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -77,10 +77,12 @@ | ||
| import code | ||
| import glob | ||
| import token | ||
| import types | ||
| import codeop | ||
| import pprint | ||
| import signal | ||
| import inspect | ||
| import textwrap | ||
| import tokenize | ||
| import traceback | ||
| import linecache | ||
| @@ -624,11 +626,96 @@ def _disable_command_completion(self): | ||
| self.completenames = completenames | ||
| return | ||
| def _exec_in_closure(self, source, globals, locals): | ||
| """ Run source code in closure so code object created within source | ||
| can find variables in locals correctly | ||
| returns True if the source is executed, False otherwise | ||
| """ | ||
| # Determine if the source should be executed in closure. Only when the | ||
| # source compiled to multiple code objects, we should use this feature. | ||
| # Otherwise, we can just raise an exception and normal exec will be used. | ||
| code = compile(source, "<string>", "exec") | ||
| if not any(isinstance(const, CodeType) for const in code.co_consts): | ||
| return False | ||
| # locals could be a proxy which does not support pop | ||
| # copy it first to avoid modifying the original locals | ||
| locals_copy = dict(locals) | ||
| locals_copy["__pdb_eval__"] = { | ||
| "result": None, | ||
| "write_back": {} | ||
| } | ||
brandtbucher marked this conversation as resolved. Show resolvedHide resolvedUh oh!There was an error while loading.Please reload this page. | ||
| # If the source is an expression, we need to print its value | ||
| try: | ||
| compile(source, "<string>", "eval") | ||
| except SyntaxError: | ||
| pass | ||
| else: | ||
| source = "__pdb_eval__['result'] = " + source | ||
| # Add write-back to update the locals | ||
| source = ("try:\n" + | ||
| textwrap.indent(source, " ") + "\n" + | ||
| "finally:\n" + | ||
| " __pdb_eval__['write_back'] = locals()") | ||
| # Build a closure source code with freevars from locals like: | ||
| # def __pdb_outer(): | ||
| # var = None | ||
| # def __pdb_scope(): # This is the code object we want to execute | ||
| # nonlocal var | ||
| # <source> | ||
| # return __pdb_scope.__code__ | ||
| source_with_closure = ("def __pdb_outer():\n" + | ||
| "\n".join(f" {var} = None" for var in locals_copy) + "\n" + | ||
| " def __pdb_scope():\n" + | ||
| "\n".join(f" nonlocal {var}" for var in locals_copy) + "\n" + | ||
| textwrap.indent(source, " ") + "\n" + | ||
| " return __pdb_scope.__code__" | ||
| ) | ||
| # Get the code object of __pdb_scope() | ||
| # The exec fills locals_copy with the __pdb_outer() function and we can call | ||
| # that to get the code object of __pdb_scope() | ||
| ns = {} | ||
| try: | ||
| exec(source_with_closure, {}, ns) | ||
| except Exception: | ||
| return False | ||
| code = ns["__pdb_outer"]() | ||
| cells = tuple(types.CellType(locals_copy.get(var)) for var in code.co_freevars) | ||
| try: | ||
| exec(code, globals, locals_copy, closure=cells) | ||
| except Exception: | ||
| return False | ||
brandtbucher marked this conversation as resolved. Show resolvedHide resolvedUh oh!There was an error while loading.Please reload this page. | ||
| # get the data we need from the statement | ||
| pdb_eval = locals_copy["__pdb_eval__"] | ||
| # __pdb_eval__ should not be updated back to locals | ||
| pdb_eval["write_back"].pop("__pdb_eval__") | ||
brandtbucher marked this conversation as resolved. Show resolvedHide resolvedUh oh!There was an error while loading.Please reload this page. | ||
| # Write all local variables back to locals | ||
| locals.update(pdb_eval["write_back"]) | ||
| eval_result = pdb_eval["result"] | ||
| if eval_result is not None: | ||
| print(repr(eval_result)) | ||
| return True | ||
| def default(self, line): | ||
| if line[:1] == '!': line = line[1:].strip() | ||
| locals = self.curframe_locals | ||
| globals = self.curframe.f_globals | ||
| try: | ||
| buffer = line | ||
| if (code := codeop.compile_command(line + '\n', '<stdin>', 'single')) is None: | ||
| # Multi-line mode | ||
| with self._disable_command_completion(): | ||
| @@ -661,7 +748,8 @@ def default(self, line): | ||
| sys.stdin = self.stdin | ||
| sys.stdout = self.stdout | ||
| sys.displayhook = self.displayhook | ||
| if not self._exec_in_closure(buffer, globals, locals): | ||
| exec(code, globals, locals) | ||
| finally: | ||
| sys.stdout = save_stdout | ||
| sys.stdin = save_stdin | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.Learn more about bidirectional Unicode characters
3 changes: 3 additions & 0 deletionsMisc/NEWS.d/next/Library/2023-10-20-03-50-17.gh-issue-83151.bcsD40.rst
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,3 @@ | ||
| Enabled arbitrary statements and evaluations in :mod:`pdb` shell to access the | ||
| local variables of the current frame, which made it possible for multi-scope | ||
| code like generators or nested function to work. |
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.