From 85e11bf4a134a5878fec847d8c0eba413b52052b Mon Sep 17 00:00:00 2001 From: Gertjan van Zwieten Date: Mon, 7 Aug 2023 14:12:07 +0200 Subject: [PATCH 1/2] escape class name in regular expression This patch escapes the class name before embedding it in the regular expression for `pat` in `doctest.DocTestFinder._find_lineno`. While class names do not ordinarily contain special characters, it is possible to encounter these when a class is created dynamically. Escaping the name will correctly return `None` in this scenario, rather than potentially matching a different class or raising `re.error` depending on the symbols used. --- Lib/doctest.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Lib/doctest.py b/Lib/doctest.py index 2776d74bf9b586..a63df46a112e64 100644 --- a/Lib/doctest.py +++ b/Lib/doctest.py @@ -1110,7 +1110,7 @@ def _find_lineno(self, obj, source_lines): if source_lines is None: return None pat = re.compile(r'^\s*class\s*%s\b' % - getattr(obj, '__name__', '-')) + re.escape(getattr(obj, '__name__', '-'))) for i, line in enumerate(source_lines): if pat.match(line): lineno = i From 0e509f2b877d4eed051d43c75980e08e1a9940c2 Mon Sep 17 00:00:00 2001 From: Gertjan van Zwieten Date: Mon, 7 Aug 2023 15:12:11 +0200 Subject: [PATCH 2/2] add news entry --- .../next/Library/2023-08-07-14-12-07.gh-issue-107715.238r2f.rst | 1 + 1 file changed, 1 insertion(+) create mode 100644 Misc/NEWS.d/next/Library/2023-08-07-14-12-07.gh-issue-107715.238r2f.rst diff --git a/Misc/NEWS.d/next/Library/2023-08-07-14-12-07.gh-issue-107715.238r2f.rst b/Misc/NEWS.d/next/Library/2023-08-07-14-12-07.gh-issue-107715.238r2f.rst new file mode 100644 index 00000000000000..cd2a5d0d5324a2 --- /dev/null +++ b/Misc/NEWS.d/next/Library/2023-08-07-14-12-07.gh-issue-107715.238r2f.rst @@ -0,0 +1 @@ +Fix `doctest.DocTestFinder.find` in presence of class names with special characters. Patch by Gertjan van Zwieten.