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 */ };