Skip to content

Commit 03b4d50

Browse files
committed
Issue #15424: Add a __sizeof__ implementation for array objects.
Patch by Ludwig Hähne.
1 parent 7dbee38 commit 03b4d50

File tree

4 files changed

+32
-0
lines changed

4 files changed

+32
-0
lines changed

Lib/test/test_array.py

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -988,6 +988,19 @@ def test_create_from_bytes(self):
988988
a = array.array('H', b"1234")
989989
self.assertEqual(len(a) * a.itemsize, 4)
990990

991+
@support.cpython_only
992+
def test_sizeof_with_buffer(self):
993+
a = array.array(self.typecode, self.example)
994+
basesize = support.calcvobjsize('4Pi')
995+
buffer_size = a.buffer_info()[1] * a.itemsize
996+
support.check_sizeof(self, a, basesize + buffer_size)
997+
998+
@support.cpython_only
999+
def test_sizeof_without_buffer(self):
1000+
a = array.array(self.typecode)
1001+
basesize = support.calcvobjsize('4Pi')
1002+
support.check_sizeof(self, a, basesize)
1003+
9911004

9921005
class StringTest(BaseTest):
9931006

Misc/ACKS

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -434,6 +434,7 @@ Jim Hugunin
434434
Greg Humphreys
435435
Eric Huss
436436
Jeremy Hylton
437+
Ludwig Hähne
437438
Gerhard Häring
438439
Fredrik Håård
439440
Mihai Ibanescu

Misc/NEWS

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -101,6 +101,9 @@ Core and Builtins
101101
Library
102102
-------
103103

104+
- Issue #15424: Add a __sizeof__ implementation for array objects.
105+
Patch by Ludwig Hähne.
106+
104107
- Issue #13052: Fix IDLE crashing when replace string in Search/Replace dialog
105108
ended with '\'. Patch by Roger Serwy.
106109

Modules/arraymodule.c

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1510,6 +1510,19 @@ array.tobytes().decode() to obtain a unicode string from\n\
15101510
an array of some other type.");
15111511

15121512

1513+
static PyObject *
1514+
array_sizeof(arrayobject *self, PyObject *unused)
1515+
{
1516+
Py_ssize_t res;
1517+
res = sizeof(arrayobject) + self->allocated * self->ob_descr->itemsize;
1518+
return PyLong_FromSsize_t(res);
1519+
}
1520+
1521+
PyDoc_STRVAR(sizeof_doc,
1522+
"__sizeof__() -> int\n\
1523+
\n\
1524+
Size of the array in memory, in bytes.");
1525+
15131526

15141527
/*********************** Pickling support ************************/
15151528

@@ -2077,6 +2090,8 @@ static PyMethodDef array_methods[] = {
20772090
tobytes_doc},
20782091
{"tounicode", (PyCFunction)array_tounicode, METH_NOARGS,
20792092
tounicode_doc},
2093+
{"__sizeof__", (PyCFunction)array_sizeof, METH_NOARGS,
2094+
sizeof_doc},
20802095
{NULL, NULL} /* sentinel */
20812096
};
20822097

0 commit comments

Comments
 (0)