Skip to content

Commit 5ce819f

Browse files
GH-94254: Make _struct module types immutable (GH-94269)
(cherry picked from commit 17ed560) Co-authored-by: Kumar Aditya <[email protected]>
1 parent ad23df9 commit 5ce819f

File tree

3 files changed

+17
-2
lines changed

3 files changed

+17
-2
lines changed

Lib/test/test_struct.py

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -689,6 +689,18 @@ def test__struct_reference_cycle_cleaned_up(self):
689689
self.assertIsNone(
690690
module_ref(), "_struct module was not garbage collected")
691691

692+
@support.cpython_only
693+
def test__struct_types_immutable(self):
694+
# See https://github.com/python/cpython/issues/94254
695+
696+
Struct = struct.Struct
697+
unpack_iterator = type(struct.iter_unpack("b", b'x'))
698+
for cls in (Struct, unpack_iterator):
699+
with self.subTest(cls=cls):
700+
with self.assertRaises(TypeError):
701+
cls.x = 1
702+
703+
692704
def test_issue35714(self):
693705
# Embedded null characters should not be allowed in format strings.
694706
for s in '\0', '2\0i', b'\0':
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Fixed types of :mod:`struct` module to be immutable. Patch by Kumar Aditya.

Modules/_struct.c

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1741,7 +1741,8 @@ static PyType_Spec unpackiter_type_spec = {
17411741
"_struct.unpack_iterator",
17421742
sizeof(unpackiterobject),
17431743
0,
1744-
Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,
1744+
(Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
1745+
Py_TPFLAGS_IMMUTABLETYPE),
17451746
unpackiter_type_slots
17461747
};
17471748

@@ -2110,7 +2111,8 @@ static PyType_Spec PyStructType_spec = {
21102111
"_struct.Struct",
21112112
sizeof(PyStructObject),
21122113
0,
2113-
Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC | Py_TPFLAGS_BASETYPE,
2114+
(Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
2115+
Py_TPFLAGS_BASETYPE | Py_TPFLAGS_IMMUTABLETYPE),
21142116
PyStructType_slots
21152117
};
21162118

0 commit comments

Comments
 (0)