]> git.ipfire.org Git - thirdparty/Python/cpython.git/commitdiff
GH-94254: Make _struct module types immutable (#94269)
authorKumar Aditya <59607654+kumaraditya303@users.noreply.github.com>
Sun, 26 Jun 2022 10:12:01 +0000 (15:42 +0530)
committerGitHub <noreply@github.com>
Sun, 26 Jun 2022 10:12:01 +0000 (12:12 +0200)
Lib/test/test_struct.py
Misc/NEWS.d/next/Library/2022-06-25-16-27-02.gh-issue-94254.beP16v.rst [new file with mode: 0644]
Modules/_struct.c

index 8f14ed30588810f93138bf1d8085e9cf5b917a30..ab738770546c0b8168b67bff00b37c698fba51d4 100644 (file)
@@ -689,6 +689,18 @@ class StructTest(unittest.TestCase):
         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 (file)
index 0000000..81482bc
--- /dev/null
@@ -0,0 +1 @@
+Fixed types of :mod:`struct` module to be immutable. Patch by Kumar Aditya.
index 20307ad15be814334edafe3b828a0496b31c80f7..9d66568a282662674fa182c88df30b68344fdb8b 100644 (file)
@@ -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
 };
 
@@ -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
 };