Skip to content
Closed
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
21 changes: 21 additions & 0 deletions Lib/test/test_print.py
Original file line number Diff line number Diff line change
Expand Up @@ -165,6 +165,27 @@ def test_string_with_leading_whitespace(self):

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

def test_multiple_statements_on_same_line_separated_by_semicolon(self):
# Ensure multiple statements on same line produces correct hint
python2_print_str = '''x = 1
print x; pass
'''
with self.assertRaises(SyntaxError) as context:
exec(python2_print_str)

self.assertIn('print(x)', str(context.exception))

def test_multiple_statements_on_same_line(self):
# Ensure multiple statements on same line like a loop or conditional
# statement produces correct hint
python2_print_str = '''import sys
for p in sys.path: print p
'''
with self.assertRaises(SyntaxError) as context:
exec(python2_print_str)

self.assertIn('print(p)', 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,2 @@
print suggestion produces correct syntax hint when multiple statements are
used on the same line. Patch by Sanyam Khurana.
19 changes: 9 additions & 10 deletions Objects/exceptions.c
Original file line number Diff line number Diff line change
Expand Up @@ -2844,18 +2844,17 @@ _set_legacy_print_statement_msg(PySyntaxErrorObject *self, Py_ssize_t start)
if (strip_sep_obj == NULL)
return -1;

// PRINT_OFFSET is to remove `print ` word from the data.
const int PRINT_OFFSET = 6;
// PRINT_OFFSET is to accommodate the removal of `print ` word (6 chars)
// and the offset to the `print` call in the statement.
const Py_ssize_t PRINT_OFFSET = (Py_ssize_t)(6 + start);
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);
Py_ssize_t text_len = PyUnicode_GET_LENGTH(self->text);
const int RIGHT_OFFSET = PyUnicode_FindChar(self->text, ';', PRINT_OFFSET, text_len, 1);
if (RIGHT_OFFSET != -1)
// Normal case when multiple statements are not on the same line separated by `;`
text_len = RIGHT_OFFSET;
PyObject *data = PyUnicode_Substring(self->text, PRINT_OFFSET, text_len);
if (data == NULL) {
Py_DECREF(strip_sep_obj);
return -1;
Expand Down