Skip to content

Commit 5daf70b

Browse files
Erlend Egeberg Aaslandvstinner
Erlend Egeberg Aasland
andauthored
bpo-43908: Make re types immutable (GH-25697)
Co-authored-by: Victor Stinner <[email protected]>
1 parent 1e7b858 commit 5daf70b

File tree

3 files changed

+17
-3
lines changed

3 files changed

+17
-3
lines changed

Lib/test/test_re.py

+12
Original file line numberDiff line numberDiff line change
@@ -2190,6 +2190,18 @@ class ImplementationTest(unittest.TestCase):
21902190
Test implementation details of the re module.
21912191
"""
21922192

2193+
@cpython_only
2194+
def test_immutable(self):
2195+
# bpo-43908: check that re types are immutable
2196+
with self.assertRaises(TypeError):
2197+
re.Match.foo = 1
2198+
with self.assertRaises(TypeError):
2199+
re.Pattern.foo = 1
2200+
with self.assertRaises(TypeError):
2201+
pat = re.compile("")
2202+
tp = type(pat.scanner(""))
2203+
tp.foo = 1
2204+
21932205
def test_overlap_table(self):
21942206
f = sre_compile._generate_overlap_table
21952207
self.assertEqual(f(""), [])
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
Make :mod:`re` types immutable. Patch by
2+
Erlend E. Aasland.

Modules/_sre.c

+3-3
Original file line numberDiff line numberDiff line change
@@ -2690,7 +2690,7 @@ static PyType_Spec pattern_spec = {
26902690
.name = "re.Pattern",
26912691
.basicsize = sizeof(PatternObject),
26922692
.itemsize = sizeof(SRE_CODE),
2693-
.flags = Py_TPFLAGS_DEFAULT,
2693+
.flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_IMMUTABLETYPE,
26942694
.slots = pattern_slots,
26952695
};
26962696

@@ -2755,7 +2755,7 @@ static PyType_Spec match_spec = {
27552755
.name = "re.Match",
27562756
.basicsize = sizeof(MatchObject),
27572757
.itemsize = sizeof(Py_ssize_t),
2758-
.flags = Py_TPFLAGS_DEFAULT,
2758+
.flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_IMMUTABLETYPE,
27592759
.slots = match_slots,
27602760
};
27612761

@@ -2781,7 +2781,7 @@ static PyType_Slot scanner_slots[] = {
27812781
static PyType_Spec scanner_spec = {
27822782
.name = "_" SRE_MODULE ".SRE_Scanner",
27832783
.basicsize = sizeof(ScannerObject),
2784-
.flags = Py_TPFLAGS_DEFAULT,
2784+
.flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_IMMUTABLETYPE,
27852785
.slots = scanner_slots,
27862786
};
27872787

0 commit comments

Comments
 (0)