From 897cbff748ca238eeafde1bfa6ac014fbe156e1f Mon Sep 17 00:00:00 2001 From: spicysharkco <321699413+spicysharkco@users.noreply.github.com> Date: Sun, 18 Oct 2026 01:59:26 +0000 Subject: [PATCH] Fix extract_function when the extracted code defines no variable If the extracted lines define no name, the new function ended with a bare "return " and the call site became " = func(v1)". Both are invalid Python. Only add the final return line and the assignment when there is at least one variable to return. Otherwise call the function as a statement. --- AUTHORS.txt | 1 + jedi/api/refactoring/extract.py | 7 +++++-- test/refactor/extract_function.py | 16 ++++++++++++++++ 3 files changed, 22 insertions(+), 2 deletions(-) diff --git a/AUTHORS.txt b/AUTHORS.txt index 64ba230a..fb5e3a50 100644 --- a/AUTHORS.txt +++ b/AUTHORS.txt @@ -71,6 +71,7 @@ Code Contributors - Dhanraj E (@Dhanu-dynamic) - Charan Rathore (@charan-rathore) - Abdullah Ahmed (@abdull-ah-med) +- spicysharkco (@spicysharkco) And a few more "anonymous" contributors. diff --git a/jedi/api/refactoring/extract.py b/jedi/api/refactoring/extract.py index 6e7df7e1..79818961 100644 --- a/jedi/api/refactoring/extract.py +++ b/jedi/api/refactoring/extract.py @@ -247,7 +247,8 @@ def extract_function(inference_state, path, module_context, name, pos, until_pos code_block = dedent(code_block) if not has_ending_return_stmt: output_var_str = ', '.join(return_variables) - code_block += 'return ' + output_var_str + '\n' + if return_variables: + code_block += 'return ' + output_var_str + '\n' # Check if we have to raise RefactoringError _check_for_non_extractables(nodes[:-1] if has_ending_return_stmt else nodes) @@ -282,8 +283,10 @@ def extract_function(inference_state, path, module_context, name, pos, until_pos else: if has_ending_return_stmt: replacement = 'return ' + function_call + '\n' - else: + elif return_variables: replacement = output_var_str + ' = ' + function_call + '\n' + else: + replacement = function_call + '\n' replacement_dct = _replace(nodes, replacement, function_code, pos, insert_before_leaf, remaining_prefix) diff --git a/test/refactor/extract_function.py b/test/refactor/extract_function.py index da2fd259..6d6ea17a 100644 --- a/test/refactor/extract_function.py +++ b/test/refactor/extract_function.py @@ -314,6 +314,22 @@ def x(v1): #bar return x x +# -------------------------------------------------- with-range-func-no-output +def x(v1): + #? 2 text {'new_name': 'func', 'until_line': 4} + print(v1) + print(v1 + 1) + return v1 +# ++++++++++++++++++++++++++++++++++++++++++++++++++ +def func(v1): + print(v1) + print(v1 + 1) + + +def x(v1): + #? 2 text {'new_name': 'func', 'until_line': 4} + func(v1) + return v1 # -------------------------------------------------- in-class-range-1 class X1: #? 9 text {'new_name': 'f', 'until_line': 4}