Serhiy Storchaka <storch...@gmail.com> added the comment:
Here is Struct.__sizeof__ patch with tests.
----------
Added file: http://bugs.python.org/file26115/struct_sizeof-2.patch
_______________________________________
Python tracker <rep...@bugs.python.org>
<http://bugs.python.org/issue14596>
_______________________________________
diff -r 53fc7f59c7bb Lib/test/test_struct.py
--- a/Lib/test/test_struct.py Sat Jun 23 20:28:32 2012 +0200
+++ b/Lib/test/test_struct.py Sat Jun 23 23:39:25 2012 +0300
@@ -572,6 +572,16 @@
s = struct.Struct('i')
s.__init__('ii')
+ 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)
diff -r 53fc7f59c7bb Modules/_struct.c
--- a/Modules/_struct.c Sat Jun 23 20:28:32 2012 +0200
+++ b/Modules/_struct.c Sat Jun 23 23:39:25 2012 +0300
@@ -1752,6 +1752,19 @@
return PyLong_FromSsize_t(self->s_size);
}
+static PyObject *
+s_sizeof(PyStructObject *self, void *unused)
+{
+ Py_ssize_t res;
+ formatcode *code;
+
+ res = sizeof(PyStructObject) + sizeof(formatcode);
+ for (code = self->s_codes; code->fmtdef != NULL; code++) {
+ res += sizeof(formatcode);
+ }
+ return PyLong_FromSsize_t(res);
+}
+
/* List of functions */
static struct PyMethodDef s_methods[] = {
@@ -1760,6 +1773,8 @@
{"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,
+ "Returns size in memory, in bytes"},
{NULL, NULL} /* sentinel */
};
_______________________________________________
Python-bugs-list mailing list
Unsubscribe:
http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com