[Python-checkins] bpo-43908: Make re types immutable (GH-25697)

vstinner webhook-mailer at python.org
Thu Apr 29 02:47:19 EDT 2021


https://github.com/python/cpython/commit/5daf70b22e72ea1a88c05975f69120b8c4e4927f
commit: 5daf70b22e72ea1a88c05975f69120b8c4e4927f
branch: master
author: Erlend Egeberg Aasland <erlend.aasland at innova.no>
committer: vstinner <vstinner at python.org>
date: 2021-04-29T08:47:11+02:00
summary:

bpo-43908: Make re types immutable (GH-25697)

Co-authored-by: Victor Stinner <vstinner at python.org>

files:
A Misc/NEWS.d/next/Core and Builtins/2021-04-26-21-20-41.bpo-43908.2L51nO.rst
M Lib/test/test_re.py
M Modules/_sre.c

diff --git a/Lib/test/test_re.py b/Lib/test/test_re.py
index bd689582523c3..96d0cdb17a7ee 100644
--- a/Lib/test/test_re.py
+++ b/Lib/test/test_re.py
@@ -2190,6 +2190,18 @@ class ImplementationTest(unittest.TestCase):
     Test implementation details of the re module.
     """
 
+    @cpython_only
+    def test_immutable(self):
+        # bpo-43908: check that re types are immutable
+        with self.assertRaises(TypeError):
+            re.Match.foo = 1
+        with self.assertRaises(TypeError):
+            re.Pattern.foo = 1
+        with self.assertRaises(TypeError):
+            pat = re.compile("")
+            tp = type(pat.scanner(""))
+            tp.foo = 1
+
     def test_overlap_table(self):
         f = sre_compile._generate_overlap_table
         self.assertEqual(f(""), [])
diff --git a/Misc/NEWS.d/next/Core and Builtins/2021-04-26-21-20-41.bpo-43908.2L51nO.rst b/Misc/NEWS.d/next/Core and Builtins/2021-04-26-21-20-41.bpo-43908.2L51nO.rst
new file mode 100644
index 0000000000000..1709351726f96
--- /dev/null
+++ b/Misc/NEWS.d/next/Core and Builtins/2021-04-26-21-20-41.bpo-43908.2L51nO.rst	
@@ -0,0 +1,2 @@
+Make :mod:`re` types immutable. Patch by
+Erlend E. Aasland.
diff --git a/Modules/_sre.c b/Modules/_sre.c
index d4bfff6e849e3..59f7551a227cd 100644
--- a/Modules/_sre.c
+++ b/Modules/_sre.c
@@ -2690,7 +2690,7 @@ static PyType_Spec pattern_spec = {
     .name = "re.Pattern",
     .basicsize = sizeof(PatternObject),
     .itemsize = sizeof(SRE_CODE),
-    .flags = Py_TPFLAGS_DEFAULT,
+    .flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_IMMUTABLETYPE,
     .slots = pattern_slots,
 };
 
@@ -2755,7 +2755,7 @@ static PyType_Spec match_spec = {
     .name = "re.Match",
     .basicsize = sizeof(MatchObject),
     .itemsize = sizeof(Py_ssize_t),
-    .flags = Py_TPFLAGS_DEFAULT,
+    .flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_IMMUTABLETYPE,
     .slots = match_slots,
 };
 
@@ -2781,7 +2781,7 @@ static PyType_Slot scanner_slots[] = {
 static PyType_Spec scanner_spec = {
     .name = "_" SRE_MODULE ".SRE_Scanner",
     .basicsize = sizeof(ScannerObject),
-    .flags = Py_TPFLAGS_DEFAULT,
+    .flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_IMMUTABLETYPE,
     .slots = scanner_slots,
 };
 



More information about the Python-checkins mailing list