Skip to content

Add Extract function refactoring to the editor context menu - #26254

Open
alanloko wants to merge 3 commits into
spyder-ide:masterfrom
alanloko:add-extract-function-refactoring
Open

Add Extract function refactoring to the editor context menu#26254
alanloko wants to merge 3 commits into
spyder-ide:masterfrom
alanloko:add-extract-function-refactoring

Conversation

@alanloko

@alanloko alanloko commented Aug 12, 2026

Copy link
Copy Markdown

Description of Changes

This PR adds an Extract function refactoring action to the editor's context menu (in the same section as Generate docstring and Format file or selection).

How it works:

  1. Select a block of code in a Python file.
  2. Right-click → Extract function.
  3. Enter a name for the new function.

The selected block is replaced by a call to the new function, and the function is created after the current scope. The refactoring is powered by rope (already available as a dependency through python-lsp-server[all]), which analyzes the block's input/output variables to build the correct signature and return value.

Implementation notes:

  • The whole operation is applied as a single undoable edit (same approach as clear_all_output), so Ctrl+Z reverts it in one step.
  • Invalid selections (incomplete statements, syntax errors) show a warning dialog with rope's error instead of failing silently.
  • The action validates that the entered name is a valid Python identifier and is only available for Python files.

Included in this PR:

  • Tests in test_extract_function.py covering: successful extraction (signature/return detection), single-step undo, no selection, invalid function name, cancelled dialog, and invalid (mid-statement) selections. Existing test_codeeditor.py and test_editing.py suites still pass locally.
  • Changelog entry under New features for 6.2.0 in changelogs/Spyder-6.md.

Issue(s) Resolved

Affirmation

By submitting this Pull Request or typing my (user)name below,
I affirm the Developer Certificate of Origin
with respect to all commits and content included in this PR,
and understand I am releasing the same under Spyder's MIT (Expat) license.

I certify the above statement is true and correct: alanloko

Selecting a block of code and choosing Extract function in the editor's
context menu extracts it into a new function using rope, which detects
the block's input/output variables to build the new function's signature
and return value. The replacement is applied as a single undoable edit.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant