[Python-checkins] GH-94254: Make _struct module types immutable (GH-94269)

miss-islington webhook-mailer at python.org
Sun Jun 26 06:45:04 EDT 2022


https://github.com/python/cpython/commit/c481cd6256f0e4493fa28f26c5902101803abadb
commit: c481cd6256f0e4493fa28f26c5902101803abadb
branch: 3.10
author: Miss Islington (bot) <31488909+miss-islington at users.noreply.github.com>
committer: miss-islington <31488909+miss-islington at users.noreply.github.com>
date: 2022-06-26T03:45:00-07:00
summary:

GH-94254: Make _struct module types immutable (GH-94269)

(cherry picked from commit 17ed560fcd0a1442485f9bd48884bbe412f35abc)

Co-authored-by: Kumar Aditya <59607654+kumaraditya303 at users.noreply.github.com>

files:
A Misc/NEWS.d/next/Library/2022-06-25-16-27-02.gh-issue-94254.beP16v.rst
M Lib/test/test_struct.py
M Modules/_struct.c

diff --git a/Lib/test/test_struct.py b/Lib/test/test_struct.py
index 5c2dfabacb1f7..5a9b5de9537b8 100644
--- a/Lib/test/test_struct.py
+++ b/Lib/test/test_struct.py
@@ -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':
diff --git a/Misc/NEWS.d/next/Library/2022-06-25-16-27-02.gh-issue-94254.beP16v.rst b/Misc/NEWS.d/next/Library/2022-06-25-16-27-02.gh-issue-94254.beP16v.rst
new file mode 100644
index 0000000000000..81482bcd4f897
--- /dev/null
+++ b/Misc/NEWS.d/next/Library/2022-06-25-16-27-02.gh-issue-94254.beP16v.rst
@@ -0,0 +1 @@
+Fixed types of :mod:`struct` module to be immutable. Patch by Kumar Aditya.
diff --git a/Modules/_struct.c b/Modules/_struct.c
index 79806ea0d9127..cf0a6fdead853 100644
--- a/Modules/_struct.c
+++ b/Modules/_struct.c
@@ -1740,7 +1740,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
 };
 
@@ -2111,7 +2112,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
 };
 



More information about the Python-checkins mailing list