]> granicus.if.org Git - python/commitdiff
Issue #15402: Add a __sizeof__ method to struct.Struct.
authorMeador Inge <meadori@gmail.com>
Mon, 23 Jul 2012 14:27:00 +0000 (09:27 -0500)
committerMeador Inge <meadori@gmail.com>
Mon, 23 Jul 2012 14:27:00 +0000 (09:27 -0500)
Initial patch by Serhiy Storchaka.

Lib/test/test_struct.py
Misc/NEWS
Modules/_struct.c

index 5a63135a1a35f8364079d1721419daf15e7c4071..caada9cadba7c257fb1f73ce04cbd7472c34a680 100644 (file)
@@ -544,6 +544,16 @@ class StructTest(unittest.TestCase):
         hugecount2 = '{}b{}H'.format(sys.maxsize//2, sys.maxsize//2)
         self.assertRaises(struct.error, struct.calcsize, hugecount2)
 
+    def test_sizeof(self):
+        self.assertGreater(sys.getsizeof(struct.Struct('BHILfdspP')),
+                           sys.getsizeof(struct.Struct('B')))
+        self.assertGreaterEqual(sys.getsizeof(struct.Struct('123B')),
+                                sys.getsizeof(struct.Struct('B')))
+        self.assertGreaterEqual(sys.getsizeof(struct.Struct('B' * 123)),
+                                sys.getsizeof(struct.Struct('123B')))
+        self.assertGreaterEqual(sys.getsizeof(struct.Struct('123xB')),
+                                sys.getsizeof(struct.Struct('B')))
+
 def test_main():
     run_unittest(StructTest)
 
index a279941eb35c2ed2cb645f62c9db811c791d55f9..ca0740ed912fa85374ed22e0215572b68e575202 100644 (file)
--- a/Misc/NEWS
+++ b/Misc/NEWS
@@ -90,6 +90,10 @@ Core and Builtins
 Library
 -------
 
+- Issue #15402: An issue in the struct module that caused sys.getsizeof to
+  return incorrect results for struct.Struct instances has been fixed.
+  Initial patch by Serhiy Storchaka.
+
 - Issue #15232: when mangle_from is True, email.Generator now correctly mangles
   lines that start with 'From' that occur in a MIME preamble or epilog.
 
index c158ebab92f2a4c4763da44e1c8ea094fd0097ee..3ede1d0188c845d4e25db7fa30b693ac76606d05 100644 (file)
@@ -1693,6 +1693,22 @@ s_get_size(PyStructObject *self, void *unused)
     return PyInt_FromSsize_t(self->s_size);
 }
 
+PyDoc_STRVAR(s_sizeof__doc__,
+"S.__sizeof__() -> size of S in memory, in bytes");
+
+static PyObject *
+s_sizeof(PyStructObject *self)
+{
+    Py_ssize_t size;
+    formatcode *code;
+
+    size = sizeof(PyStructObject) + sizeof(formatcode);
+    for (code = self->s_codes; code->fmtdef != NULL; code++) {
+        size += sizeof(formatcode);
+    }
+    return PyLong_FromSsize_t(size);
+}
+
 /* List of functions */
 
 static struct PyMethodDef s_methods[] = {
@@ -1701,6 +1717,7 @@ static struct PyMethodDef s_methods[] = {
     {"unpack",          s_unpack,       METH_O, s_unpack__doc__},
     {"unpack_from",     (PyCFunction)s_unpack_from, METH_VARARGS|METH_KEYWORDS,
                     s_unpack_from__doc__},
+    {"__sizeof__",      (PyCFunction)s_sizeof, METH_NOARGS, s_sizeof__doc__},
     {NULL,       NULL}          /* sentinel */
 };