diff --git a/Lib/test/test_exceptions.py b/Lib/test/test_exceptions.py index 72c86eecae2539..f4f2011a51aed7 100644 --- a/Lib/test/test_exceptions.py +++ b/Lib/test/test_exceptions.py @@ -2195,6 +2195,22 @@ def test_range_of_offsets(self): self.assertIn(expected, err.getvalue()) the_exception = exc + def test_subclass(self): + class MySyntaxError(SyntaxError): + pass + + try: + raise MySyntaxError("bad bad", ("bad.py", 1, 2, "abcdefg", 1, 7)) + except SyntaxError as exc: + with support.captured_stderr() as err: + sys.__excepthook__(*sys.exc_info()) + self.assertIn(""" + File "bad.py", line 1 + abcdefg + ^^^^^ +""", err.getvalue()) + + def test_encodings(self): self.addCleanup(unlink, TESTFN) source = ( diff --git a/Misc/NEWS.d/next/Core_and_Builtins/2024-12-03-12-17-36.gh-issue-111609.UHpQY9.rst b/Misc/NEWS.d/next/Core_and_Builtins/2024-12-03-12-17-36.gh-issue-111609.UHpQY9.rst new file mode 100644 index 00000000000000..1f63a6f510cff3 --- /dev/null +++ b/Misc/NEWS.d/next/Core_and_Builtins/2024-12-03-12-17-36.gh-issue-111609.UHpQY9.rst @@ -0,0 +1 @@ +Respect *end_offset* in :exc:`SyntaxError` subclasses. diff --git a/Python/pythonrun.c b/Python/pythonrun.c index 5f3d249df45814..cf84573a8e6147 100644 --- a/Python/pythonrun.c +++ b/Python/pythonrun.c @@ -538,43 +538,37 @@ parse_syntax_error(PyObject *err, PyObject **message, PyObject **filename, *offset = hold; } - if (Py_TYPE(err) == (PyTypeObject*)PyExc_SyntaxError) { - v = PyObject_GetAttr(err, &_Py_ID(end_lineno)); - if (!v) { - PyErr_Clear(); - *end_lineno = *lineno; - } - else if (v == Py_None) { - *end_lineno = *lineno; - Py_DECREF(v); - } else { - hold = PyLong_AsSsize_t(v); - Py_DECREF(v); - if (hold < 0 && PyErr_Occurred()) - goto finally; - *end_lineno = hold; - } - - v = PyObject_GetAttr(err, &_Py_ID(end_offset)); - if (!v) { - PyErr_Clear(); - *end_offset = -1; - } - else if (v == Py_None) { - *end_offset = -1; - Py_DECREF(v); - } else { - hold = PyLong_AsSsize_t(v); - Py_DECREF(v); - if (hold < 0 && PyErr_Occurred()) - goto finally; - *end_offset = hold; - } - } else { - // SyntaxError subclasses + v = PyObject_GetAttr(err, &_Py_ID(end_lineno)); + if (!v) { + PyErr_Clear(); *end_lineno = *lineno; + } + else if (v == Py_None) { + *end_lineno = *lineno; + Py_DECREF(v); + } else { + hold = PyLong_AsSsize_t(v); + Py_DECREF(v); + if (hold < 0 && PyErr_Occurred()) + goto finally; + *end_lineno = hold; + } + + v = PyObject_GetAttr(err, &_Py_ID(end_offset)); + if (!v) { + PyErr_Clear(); *end_offset = -1; } + else if (v == Py_None) { + *end_offset = -1; + Py_DECREF(v); + } else { + hold = PyLong_AsSsize_t(v); + Py_DECREF(v); + if (hold < 0 && PyErr_Occurred()) + goto finally; + *end_offset = hold; + } v = PyObject_GetAttr(err, &_Py_ID(text)); if (!v)