Skip to content

Commit d5b19e7

Browse files
authored
add extra newline to execute when returning dictionary (#24784)
Resolves: #22469 Need one more extra line to "execute" on behalf of user when returning dictionary.
1 parent b4e1ddb commit d5b19e7

File tree

2 files changed

+56
-0
lines changed

2 files changed

+56
-0
lines changed

python_files/normalizeSelection.py

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -120,8 +120,12 @@ def normalize_lines(selection):
120120

121121
# Insert a newline between each top-level statement, and append a newline to the selection.
122122
source = "\n".join(statements) + "\n"
123+
# If selection ends with trailing dictionary or list, remove last unnecessary newline.
123124
if selection[-2] == "}" or selection[-2] == "]":
124125
source = source[:-1]
126+
# If the selection contains trailing return dictionary, insert newline to trigger execute.
127+
if check_end_with_return_dict(selection):
128+
source = source + "\n"
125129
except Exception:
126130
# If there's a problem when parsing statements,
127131
# append a blank line to end the block and send it as-is.
@@ -134,6 +138,11 @@ def normalize_lines(selection):
134138
min_key = None
135139

136140

141+
def check_end_with_return_dict(code):
142+
stripped_code = code.strip()
143+
return stripped_code.endswith("}") and "return {" in stripped_code.strip()
144+
145+
137146
def check_exact_exist(top_level_nodes, start_line, end_line):
138147
return [
139148
node

python_files/tests/test_normalize_selection.py

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -268,3 +268,50 @@ def test_list_comp(self):
268268
result = normalizeSelection.normalize_lines(src)
269269

270270
assert result == expected
271+
272+
def test_return_dict(self):
273+
importlib.reload(normalizeSelection)
274+
src = textwrap.dedent(
275+
"""\
276+
def get_dog(name, breed):
277+
return {'name': name, 'breed': breed}
278+
"""
279+
)
280+
281+
expected = textwrap.dedent(
282+
"""\
283+
def get_dog(name, breed):
284+
return {'name': name, 'breed': breed}
285+
286+
"""
287+
)
288+
289+
result = normalizeSelection.normalize_lines(src)
290+
291+
assert result == expected
292+
293+
def test_return_dict2(self):
294+
importlib.reload(normalizeSelection)
295+
src = textwrap.dedent(
296+
"""\
297+
def get_dog(name, breed):
298+
return {'name': name, 'breed': breed}
299+
300+
dog = get_dog('Ahri', 'Pomeranian')
301+
print(dog)
302+
"""
303+
)
304+
305+
expected = textwrap.dedent(
306+
"""\
307+
def get_dog(name, breed):
308+
return {'name': name, 'breed': breed}
309+
310+
dog = get_dog('Ahri', 'Pomeranian')
311+
print(dog)
312+
"""
313+
)
314+
315+
result = normalizeSelection.normalize_lines(src)
316+
317+
assert result == expected

0 commit comments

Comments
 (0)