Skip to content

Commit d57f26c

Browse files
CuriousLearnerncoghlan
authored andcommitted
bpo-32028: Fix suggestions for indented print statements (GH-4688)
The suggested replacement for print statements previously failed to account for leading whitespace and hence could end up including unwanted text in the proposed call to the print builtin. Patch by Sanyam Khurana.
1 parent 6690bb9 commit d57f26c

File tree

3 files changed

+23
-5
lines changed

3 files changed

+23
-5
lines changed

Lib/test/test_print.py

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -156,6 +156,15 @@ def test_string_with_excessive_whitespace(self):
156156

157157
self.assertIn('print("Hello World", end=" ")', str(context.exception))
158158

159+
def test_string_with_leading_whitespace(self):
160+
python2_print_str = '''if 1:
161+
print "Hello World"
162+
'''
163+
with self.assertRaises(SyntaxError) as context:
164+
exec(python2_print_str)
165+
166+
self.assertIn('print("Hello World")', str(context.exception))
167+
159168
def test_stream_redirection_hint_for_py2_migration(self):
160169
# Test correct hint produced for Py2 redirection syntax
161170
with self.assertRaises(TypeError) as context:
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
Leading whitespace is now correctly ignored when generating suggestions
2+
for converting Py2 print statements to Py3 builtin print function calls.
3+
Patch by Sanyam Khurana.

Objects/exceptions.c

Lines changed: 11 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -2846,17 +2846,23 @@ _set_legacy_print_statement_msg(PySyntaxErrorObject *self, Py_ssize_t start)
28462846

28472847
// PRINT_OFFSET is to remove `print ` word from the data.
28482848
const int PRINT_OFFSET = 6;
2849-
Py_ssize_t text_len = PyUnicode_GET_LENGTH(self->text);
2850-
PyObject *data = PyUnicode_Substring(self->text, PRINT_OFFSET, text_len);
2851-
2849+
const int STRIP_BOTH = 2;
2850+
// Issue 32028: Handle case when whitespace is used with print call
2851+
PyObject *initial_data = _PyUnicode_XStrip(self->text, STRIP_BOTH, strip_sep_obj);
2852+
if (initial_data == NULL) {
2853+
Py_DECREF(strip_sep_obj);
2854+
return -1;
2855+
}
2856+
Py_ssize_t text_len = PyUnicode_GET_LENGTH(initial_data);
2857+
PyObject *data = PyUnicode_Substring(initial_data, PRINT_OFFSET, text_len);
2858+
Py_DECREF(initial_data);
28522859
if (data == NULL) {
28532860
Py_DECREF(strip_sep_obj);
28542861
return -1;
28552862
}
2856-
PyObject *new_data = _PyUnicode_XStrip(data, 2, strip_sep_obj);
2863+
PyObject *new_data = _PyUnicode_XStrip(data, STRIP_BOTH, strip_sep_obj);
28572864
Py_DECREF(data);
28582865
Py_DECREF(strip_sep_obj);
2859-
28602866
if (new_data == NULL) {
28612867
return -1;
28622868
}

0 commit comments

Comments
 (0)