Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 80dd1af

Browse files
committed
Issue #15424: Add a __sizeof__ implementation for array objects.
Patch by Ludwig Hähne.
2 parents 688a551 + 03b4d50 commit 80dd1af

4 files changed

Lines changed: 32 additions & 0 deletions

File tree

Lib/test/test_array.py

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

1018+
@support.cpython_only
1019+
def test_sizeof_with_buffer(self):
1020+
a = array.array(self.typecode, self.example)
1021+
basesize = support.calcvobjsize('Pn2Pi')
1022+
buffer_size = a.buffer_info()[1] * a.itemsize
1023+
support.check_sizeof(self, a, basesize + buffer_size)
1024+
1025+
@support.cpython_only
1026+
def test_sizeof_without_buffer(self):
1027+
a = array.array(self.typecode)
1028+
basesize = support.calcvobjsize('Pn2Pi')
1029+
support.check_sizeof(self, a, basesize)
1030+
10181031

10191032
class StringTest(BaseTest):
10201033

Misc/ACKS

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -479,6 +479,7 @@ Greg Humphreys
479479
Eric Huss
480480
Taihyun Hwang
481481
Jeremy Hylton
482+
Ludwig Hähne
482483
Gerhard Häring
483484
Fredrik Håård
484485
Catalin Iacob

Misc/NEWS

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -80,6 +80,9 @@ Core and Builtins
8080
Library
8181
-------
8282

83+
- Issue #15424: Add a __sizeof__ implementation for array objects.
84+
Patch by Ludwig Hähne.
85+
8386
- Issue #15576: Allow extension modules to act as a package's __init__ module.
8487

8588
- Issue #15502: Have importlib.invalidate_caches() work on sys.meta_path

Modules/arraymodule.c

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

15691569

1570+
static PyObject *
1571+
array_sizeof(arrayobject *self, PyObject *unused)
1572+
{
1573+
Py_ssize_t res;
1574+
res = sizeof(arrayobject) + self->allocated * self->ob_descr->itemsize;
1575+
return PyLong_FromSsize_t(res);
1576+
}
1577+
1578+
PyDoc_STRVAR(sizeof_doc,
1579+
"__sizeof__() -> int\n\
1580+
\n\
1581+
Size of the array in memory, in bytes.");
1582+
15701583

15711584
/*********************** Pickling support ************************/
15721585

@@ -2143,6 +2156,8 @@ static PyMethodDef array_methods[] = {
21432156
tobytes_doc},
21442157
{"tounicode", (PyCFunction)array_tounicode, METH_NOARGS,
21452158
tounicode_doc},
2159+
{"__sizeof__", (PyCFunction)array_sizeof, METH_NOARGS,
2160+
sizeof_doc},
21462161
{NULL, NULL} /* sentinel */
21472162
};
21482163

0 commit comments

Comments
 (0)