diff --git a/Lib/test/test_traceback.py b/Lib/test/test_traceback.py --- a/Lib/test/test_traceback.py +++ b/Lib/test/test_traceback.py @@ -32,6 +32,9 @@ def syntax_error_bad_indentation(self): compile("def spam():\n print(1)\n print(2)", "?", "exec") + def syntax_error_bad_indentation2(self): + compile(" print(2)", "?", "exec") + def test_caret(self): err = self.get_exception_format(self.syntax_error_with_caret, SyntaxError) @@ -43,8 +46,8 @@ err = self.get_exception_format(self.syntax_error_with_caret_2, SyntaxError) self.assertIn("^", err[2]) # third line has caret - self.assertTrue(err[2].count('\n') == 1) # and no additional newline - self.assertTrue(err[1].find("+") == err[2].find("^")) # in the right place + self.assertEqual(err[2].count('\n'), 1) # and no additional newline + self.assertEqual(err[1].find("+"), err[2].find("^")) # in the right place def test_nocaret(self): exc = SyntaxError("error", ("x.py", 23, None, "bad syntax")) @@ -60,6 +63,13 @@ self.assertIn("^", err[2]) self.assertEqual(err[1].find(")"), err[2].find("^")) + err = self.get_exception_format(self.syntax_error_bad_indentation2, + IndentationError) + self.assertEqual(len(err), 4) + self.assertEqual(err[1].strip(), "print(2)") + self.assertIn("^", err[2]) + self.assertEqual(err[1].find("p"), err[2].find("^")) + def test_base_exception(self): # Test that exceptions derived from BaseException are formatted right e = KeyboardInterrupt() diff --git a/Lib/traceback.py b/Lib/traceback.py --- a/Lib/traceback.py +++ b/Lib/traceback.py @@ -226,11 +226,12 @@ if badline is not None: lines.append(' %s\n' % badline.strip()) if offset is not None: - caretspace = badline.rstrip('\n')[:offset].lstrip() + caretspace = badline.rstrip('\n') + offset = min(len(caretspace), offset) - 1 + caretspace = caretspace[:offset].lstrip() # non-space whitespace (likes tabs) must be kept for alignment caretspace = ((c.isspace() and c or ' ') for c in caretspace) - # only three spaces to account for offset1 == pos 0 - lines.append(' %s^\n' % ''.join(caretspace)) + lines.append(' %s^\n' % ''.join(caretspace)) msg = value.msg or "" lines.append("%s: %s\n" % (stype, msg)) return lines