From 462bfec580755011ff2a4508ad036cbc7c8e9324 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?B=C3=A9n=C3=A9dikt=20Tran?= <10796600+picnixz@users.noreply.github.com> Date: Wed, 9 Jul 2025 15:41:24 +0200 Subject: [PATCH] fix `IndexError` in `pydoc.replace` --- Lib/pydoc.py | 8 +++++--- .../2025-07-12-13-21-34.gh-issue-136572.PLssWH.rst | 3 +++ 2 files changed, 8 insertions(+), 3 deletions(-) create mode 100644 Misc/NEWS.d/next/Library/2025-07-12-13-21-34.gh-issue-136572.PLssWH.rst diff --git a/Lib/pydoc.py b/Lib/pydoc.py index d508fb70ea429e..8a3eaaf4424045 100644 --- a/Lib/pydoc.py +++ b/Lib/pydoc.py @@ -262,9 +262,11 @@ def isdata(object): def replace(text, *pairs): """Do a series of global replacements on a string.""" - while pairs: - text = pairs[1].join(text.split(pairs[0])) - pairs = pairs[2:] + if len(pairs) % 2: + # len(pairs) must be even, so len(pairs) + 1 must be odd + raise TypeError("an odd number of arguments must be given") + for ind in range(0, len(pairs), 2): + text = pairs[ind + 1].join(text.split(pairs[ind])) return text def cram(text, maxlen): diff --git a/Misc/NEWS.d/next/Library/2025-07-12-13-21-34.gh-issue-136572.PLssWH.rst b/Misc/NEWS.d/next/Library/2025-07-12-13-21-34.gh-issue-136572.PLssWH.rst new file mode 100644 index 00000000000000..726cc95e43c92e --- /dev/null +++ b/Misc/NEWS.d/next/Library/2025-07-12-13-21-34.gh-issue-136572.PLssWH.rst @@ -0,0 +1,3 @@ +:func:`!pydoc.replace` now raises a :exc:`TypeError` instead of an +:exc:`IndexError` when the number of variadic arguments is odd (or +equivalently, if the total number of arguments is even).