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.
This commit is contained in:
spicysharkco committed 2026-10-18 02:07:55 +00:00
1 parent 2af1a0f394
commit 897cbff748
3 files changed
+21 -1

No files matched your search

+1
View File
@@ -71,6 +71,7 @@ Code Contributors
- Dhanraj E (@Dhanu-dynamic) <dhanraj@labs.digiscrypt.com> - Dhanraj E (@Dhanu-dynamic) <dhanraj@labs.digiscrypt.com>
- Charan Rathore (@charan-rathore) - Charan Rathore (@charan-rathore)
- Abdullah Ahmed (@abdull-ah-med) - Abdullah Ahmed (@abdull-ah-med)
- spicysharkco (@spicysharkco)
And a few more "anonymous" contributors. And a few more "anonymous" contributors.
+4 -1
View File
@@ -247,6 +247,7 @@ def extract_function(inference_state, path, module_context, name, pos, until_pos
code_block = dedent(code_block) code_block = dedent(code_block)
if not has_ending_return_stmt: if not has_ending_return_stmt:
output_var_str = ', '.join(return_variables) output_var_str = ', '.join(return_variables)
if return_variables:
code_block += 'return ' + output_var_str + '\n' code_block += 'return ' + output_var_str + '\n'
# Check if we have to raise RefactoringError # Check if we have to raise RefactoringError
@@ -282,8 +283,10 @@ def extract_function(inference_state, path, module_context, name, pos, until_pos
else: else:
if has_ending_return_stmt: if has_ending_return_stmt:
replacement = 'return ' + function_call + '\n' replacement = 'return ' + function_call + '\n'
else: elif return_variables:
replacement = output_var_str + ' = ' + function_call + '\n' replacement = output_var_str + ' = ' + function_call + '\n'
else:
replacement = function_call + '\n'
replacement_dct = _replace(nodes, replacement, function_code, pos, replacement_dct = _replace(nodes, replacement, function_code, pos,
insert_before_leaf, remaining_prefix) insert_before_leaf, remaining_prefix)
+16
View File
@@ -314,6 +314,22 @@ def x(v1):
#bar #bar
return x return x
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 # -------------------------------------------------- in-class-range-1
class X1: class X1:
#? 9 text {'new_name': 'f', 'until_line': 4} #? 9 text {'new_name': 'f', 'until_line': 4}