Skip to content

bpo-32028: Fix custom print suggestion having leading whitespace in print statement #4688

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 7 commits into from
Jan 20, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions Lib/test/test_print.py
Original file line number Diff line number Diff line change
Expand Up @@ -156,6 +156,15 @@ def test_string_with_excessive_whitespace(self):

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

def test_string_with_leading_whitespace(self):
python2_print_str = '''if 1:
print "Hello World"
'''
with self.assertRaises(SyntaxError) as context:
exec(python2_print_str)

self.assertIn('print("Hello World")', str(context.exception))

def test_stream_redirection_hint_for_py2_migration(self):
# Test correct hint produced for Py2 redirection syntax
with self.assertRaises(TypeError) as context:
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
Leading whitespace is now correctly ignored when generating suggestions
for converting Py2 print statements to Py3 builtin print function calls.
Patch by Sanyam Khurana.
16 changes: 11 additions & 5 deletions Objects/exceptions.c
Original file line number Diff line number Diff line change
Expand Up @@ -2846,17 +2846,23 @@ _set_legacy_print_statement_msg(PySyntaxErrorObject *self, Py_ssize_t start)

// PRINT_OFFSET is to remove `print ` word from the data.
const int PRINT_OFFSET = 6;
Py_ssize_t text_len = PyUnicode_GET_LENGTH(self->text);
PyObject *data = PyUnicode_Substring(self->text, PRINT_OFFSET, text_len);

const int STRIP_BOTH = 2;
// Issue 32028: Handle case when whitespace is used with print call
PyObject *initial_data = _PyUnicode_XStrip(self->text, STRIP_BOTH, strip_sep_obj);
if (initial_data == NULL) {
Py_DECREF(strip_sep_obj);
return -1;
}
Py_ssize_t text_len = PyUnicode_GET_LENGTH(initial_data);
PyObject *data = PyUnicode_Substring(initial_data, PRINT_OFFSET, text_len);
Py_DECREF(initial_data);
if (data == NULL) {
Py_DECREF(strip_sep_obj);
return -1;
}
PyObject *new_data = _PyUnicode_XStrip(data, 2, strip_sep_obj);
PyObject *new_data = _PyUnicode_XStrip(data, STRIP_BOTH, strip_sep_obj);
Py_DECREF(data);
Py_DECREF(strip_sep_obj);

if (new_data == NULL) {
return -1;
}
Expand Down