diff --git a/Doc/library/re.rst b/Doc/library/re.rst index 3f03f0341d81661..fd8eadec4589107 100644 --- a/Doc/library/re.rst +++ b/Doc/library/re.rst @@ -951,6 +951,8 @@ Functions .. versionchanged:: 3.7 Non-empty matches can now start just after a previous empty match. + .. versionchanged:: 3.13 + Negative start and end indices will no longer be truncated to zero in Python 3.15. .. function:: finditer(pattern, string, flags=0) @@ -962,6 +964,8 @@ Functions .. versionchanged:: 3.7 Non-empty matches can now start just after a previous empty match. + .. versionchanged:: 3.13 + Negative start and end indices will no longer be truncated to zero in Python 3.15. .. function:: sub(pattern, repl, string, count=0, flags=0) diff --git a/Lib/test/test_re.py b/Lib/test/test_re.py index a6f5af17d7d51ba..154255cbd30cc1b 100644 --- a/Lib/test/test_re.py +++ b/Lib/test/test_re.py @@ -441,6 +441,18 @@ def test_bug_117612(self): self.assertEqual(re.findall(r"(a|(b))", "aba"), [("a", ""),("b", "b"),("a", "")]) + def test_bug_7940_raises_future_warnings(self): + """Test to ensure the FutureWarnings are raised.""" + pat = re.compile(".") + with self.assertWarns(FutureWarning) as cm: + pat.findall("abcd", -1, 1) + self.assertEqual(str(cm.warning), "Negative start index will not " + "be truncated to zero in Python 3.15") + with self.assertWarns(FutureWarning) as cm: + pat.findall("abcd", 1, -1) + self.assertEqual(str(cm.warning), "Negative end index will not " + "be truncated to zero in Python 3.15") + def test_re_match(self): for string in 'a', S('a'): self.assertEqual(re.match('a', string).groups(), ()) diff --git a/Misc/NEWS.d/next/Library/2023-07-23-11-57-33.gh-issue-52188.sXC663.rst b/Misc/NEWS.d/next/Library/2023-07-23-11-57-33.gh-issue-52188.sXC663.rst new file mode 100644 index 000000000000000..f8e710b0028e337 --- /dev/null +++ b/Misc/NEWS.d/next/Library/2023-07-23-11-57-33.gh-issue-52188.sXC663.rst @@ -0,0 +1,2 @@ +Emit a FutureWarning when truncating negative start and end indices in re.finditer +and re.findall. diff --git a/Modules/_sre/sre.c b/Modules/_sre/sre.c index ddbdc9f478aab3f..3d443ab4782b4cf 100644 --- a/Modules/_sre/sre.c +++ b/Modules/_sre/sre.c @@ -453,13 +453,22 @@ state_init(SRE_STATE* state, PatternObject* pattern, PyObject* string, } /* adjust boundaries */ - if (start < 0) + if (start < 0) { + PyErr_WarnEx(PyExc_FutureWarning, + "Negative start index will not be truncated to zero in Python 3.15", + 1); start = 0; + } else if (start > length) start = length; - if (end < 0) + + if (end < 0) { + PyErr_WarnEx(PyExc_FutureWarning, + "Negative end index will not be truncated to zero in Python 3.15", + 1); end = 0; + } else if (end > length) end = length;