Skip to content

GH-94254: make _struct module types immutable #94269

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 5 commits into from
Jun 26, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions Lib/test/test_struct.py
Original file line number Diff line number Diff line change
Expand Up @@ -689,6 +689,18 @@ def test__struct_reference_cycle_cleaned_up(self):
self.assertIsNone(
module_ref(), "_struct module was not garbage collected")

@support.cpython_only
def test__struct_types_immutable(self):
# See https://github.com/python/cpython/issues/94254

Struct = struct.Struct
unpack_iterator = type(struct.iter_unpack("b", b'x'))
for cls in (Struct, unpack_iterator):
with self.subTest(cls=cls):
with self.assertRaises(TypeError):
cls.x = 1


def test_issue35714(self):
# Embedded null characters should not be allowed in format strings.
for s in '\0', '2\0i', b'\0':
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Fixed types of :mod:`struct` module to be immutable. Patch by Kumar Aditya.
6 changes: 4 additions & 2 deletions Modules/_struct.c
Original file line number Diff line number Diff line change
Expand Up @@ -1741,7 +1741,8 @@ static PyType_Spec unpackiter_type_spec = {
"_struct.unpack_iterator",
sizeof(unpackiterobject),
0,
Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,
(Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
Py_TPFLAGS_IMMUTABLETYPE),
unpackiter_type_slots
};

Expand Down Expand Up @@ -2110,7 +2111,8 @@ static PyType_Spec PyStructType_spec = {
"_struct.Struct",
sizeof(PyStructObject),
0,
Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC | Py_TPFLAGS_BASETYPE,
(Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
Py_TPFLAGS_BASETYPE | Py_TPFLAGS_IMMUTABLETYPE),
PyStructType_slots
};

Expand Down