Skip to content

Commit c481cd6

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 4b1144c commit c481cd6

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
@@ -1740,7 +1740,8 @@ static PyType_Spec unpackiter_type_spec = {
17401740
"_struct.unpack_iterator",
17411741
sizeof(unpackiterobject),
17421742
0,
1743-
Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,
1743+
(Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
1744+
Py_TPFLAGS_IMMUTABLETYPE),
17441745
unpackiter_type_slots
17451746
};
17461747

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

0 commit comments

Comments
 (0)