From c431f37faf8ede7312d926dda5cfb1c09fcce054 Mon Sep 17 00:00:00 2001 From: AZero13 Date: Fri, 26 Dec 2025 17:19:18 -0500 Subject: [PATCH] gh-143201: warnings writes the full source line instead of the truncated one The truncated object is meant to be written instead. --- Lib/test/test_warnings/__init__.py | 25 +++++++++++++++++++ ...-12-26-17-18-18.gh-issue-143201.UbXuX4.rst | 1 + Python/_warnings.c | 2 +- 3 files changed, 27 insertions(+), 1 deletion(-) create mode 100644 Misc/NEWS.d/next/Core_and_Builtins/2025-12-26-17-18-18.gh-issue-143201.UbXuX4.rst diff --git a/Lib/test/test_warnings/__init__.py b/Lib/test/test_warnings/__init__.py index 5b5d5c2f70ffd7a..fb44849870d9a9c 100644 --- a/Lib/test/test_warnings/__init__.py +++ b/Lib/test/test_warnings/__init__.py @@ -1094,6 +1094,31 @@ def test_showwarnmsg_missing(self): self.module._showwarnmsg = show self.assertIn(text, result) + def test_showwarning_fallback_truncates_source_line(self): + # gh-143201: C implementation's show_warning fallback should truncate leading whitespace + text = 'test fallback truncates source line' + with self.module.catch_warnings(): + self.module.filterwarnings("always", category=UserWarning) + + show = self.module._showwarnmsg + show_orig = getattr(self.module, 'showwarning', None) + try: + del self.module._showwarnmsg + if hasattr(self.module, 'showwarning'): + del self.module.showwarning + with support.captured_output('stderr') as stream: + def my_warn(): + self.module.warn(text) + my_warn() + result = stream.getvalue() + finally: + self.module._showwarnmsg = show + if show_orig is not None: + self.module.showwarning = show_orig + + self.assertIn('self.module.warn(text)', result) + self.assertNotIn(' self.module.warn(text)', result) + def test_showwarning_not_callable(self): orig = self.module.showwarning try: diff --git a/Misc/NEWS.d/next/Core_and_Builtins/2025-12-26-17-18-18.gh-issue-143201.UbXuX4.rst b/Misc/NEWS.d/next/Core_and_Builtins/2025-12-26-17-18-18.gh-issue-143201.UbXuX4.rst new file mode 100644 index 000000000000000..24df3a88f413fd2 --- /dev/null +++ b/Misc/NEWS.d/next/Core_and_Builtins/2025-12-26-17-18-18.gh-issue-143201.UbXuX4.rst @@ -0,0 +1 @@ +Fix an issue where the :mod:`warnings` module printed the full source line instead of the truncated one. diff --git a/Python/_warnings.c b/Python/_warnings.c index 586cec195fac680..6dad6cdb4c2e463 100644 --- a/Python/_warnings.c +++ b/Python/_warnings.c @@ -698,7 +698,7 @@ show_warning(PyThreadState *tstate, PyObject *filename, int lineno, if (truncated == NULL) goto error; - PyFile_WriteObject(sourceline, f_stderr, Py_PRINT_RAW); + PyFile_WriteObject(truncated, f_stderr, Py_PRINT_RAW); Py_DECREF(truncated); PyFile_WriteString("\n", f_stderr); }