diff --git a/Lib/test/test_warnings/__init__.py b/Lib/test/test_warnings/__init__.py index bfb43025de11405..a75160be6169c07 100644 --- a/Lib/test/test_warnings/__init__.py +++ b/Lib/test/test_warnings/__init__.py @@ -1109,6 +1109,20 @@ def test_showwarnmsg_missing(self): self.module._showwarnmsg = show self.assertIn(text, result) + def test_showwarnmsg_missing_source_line(self): + # gh-143201: the C fallback must strip the source line like Python. + lineno = sys._getframe().f_lineno + with self.module.catch_warnings(), \ + support.swap_attr(self.module, '_showwarnmsg', None), \ + support.captured_stderr() as stream: + self.module.simplefilter("always") + del self.module._showwarnmsg # use the C fallback + self.module.warn_explicit('eggs', UserWarning, __file__, lineno, + module_globals=globals()) + self.assertEqual(stream.getvalue(), py_warnings.formatwarning( + 'eggs', UserWarning, __file__, lineno, + linecache.getline(__file__, lineno))) + def test_showwarning_not_callable(self): orig = self.module.showwarning try: diff --git a/Misc/NEWS.d/next/Library/2025-12-26-17-18-18.gh-issue-143201.UbXuX4.rst b/Misc/NEWS.d/next/Library/2025-12-26-17-18-18.gh-issue-143201.UbXuX4.rst new file mode 100644 index 000000000000000..573563fd5b6ec15 --- /dev/null +++ b/Misc/NEWS.d/next/Library/2025-12-26-17-18-18.gh-issue-143201.UbXuX4.rst @@ -0,0 +1,2 @@ +Fix the C implementation of :mod:`warnings` to strip the source line like the +Python implementation. diff --git a/Python/_warnings.c b/Python/_warnings.c index 86eae5deb859691..b69992e0679b154 100644 --- a/Python/_warnings.c +++ b/Python/_warnings.c @@ -666,6 +666,7 @@ show_warning(PyThreadState *tstate, PyObject *filename, int lineno, { PyObject *f_stderr = NULL; PyObject *name; + PyObject *truncated = NULL; char lineno_str[128]; PyOS_snprintf(lineno_str, sizeof(lineno_str), ":%d: ", lineno); @@ -697,28 +698,20 @@ show_warning(PyThreadState *tstate, PyObject *filename, int lineno, /* Print " source_line\n" */ if (sourceline) { - int kind; - const void *data; - Py_ssize_t i, len; - Py_UCS4 ch; - PyObject *truncated; - - kind = PyUnicode_KIND(sourceline); - data = PyUnicode_DATA(sourceline); - len = PyUnicode_GET_LENGTH(sourceline); - for (i=0; i