Skip to content

Commit 4002d5d

Browse files
miss-islingtonncoghlan
authored andcommitted
[3.6] bpo-32028: Fix suggestions for indented print statements (GH-5249)
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. (cherry picked from commit d57f26c)
1 parent 051650a commit 4002d5d

3 files changed

Lines changed: 23 additions & 5 deletions

File tree

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
@@ -2865,17 +2865,23 @@ _set_legacy_print_statement_msg(PySyntaxErrorObject *self, Py_ssize_t start)
28652865

28662866
// PRINT_OFFSET is to remove `print ` word from the data.
28672867
const int PRINT_OFFSET = 6;
2868-
Py_ssize_t text_len = PyUnicode_GET_LENGTH(self->text);
2869-
PyObject *data = PyUnicode_Substring(self->text, PRINT_OFFSET, text_len);
2870-
2868+
const int STRIP_BOTH = 2;
2869+
// Issue 32028: Handle case when whitespace is used with print call
2870+
PyObject *initial_data = _PyUnicode_XStrip(self->text, STRIP_BOTH, strip_sep_obj);
2871+
if (initial_data == NULL) {
2872+
Py_DECREF(strip_sep_obj);
2873+
return -1;
2874+
}
2875+
Py_ssize_t text_len = PyUnicode_GET_LENGTH(initial_data);
2876+
PyObject *data = PyUnicode_Substring(initial_data, PRINT_OFFSET, text_len);
2877+
Py_DECREF(initial_data);
28712878
if (data == NULL) {
28722879
Py_DECREF(strip_sep_obj);
28732880
return -1;
28742881
}
2875-
PyObject *new_data = _PyUnicode_XStrip(data, 2, strip_sep_obj);
2882+
PyObject *new_data = _PyUnicode_XStrip(data, STRIP_BOTH, strip_sep_obj);
28762883
Py_DECREF(data);
28772884
Py_DECREF(strip_sep_obj);
2878-
28792885
if (new_data == NULL) {
28802886
return -1;
28812887
}

0 commit comments

Comments
 (0)