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

Skip to content

Commit 8f328d0

Browse files
committed
Issue #15489: Add a __sizeof__ implementation for BytesIO objects.
Patch by Serhiy Storchaka.
1 parent 10f0c50 commit 8f328d0

3 files changed

Lines changed: 26 additions & 0 deletions

File tree

Lib/test/test_memoryio.py

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -654,6 +654,17 @@ def test_setstate(self):
654654
memio.close()
655655
self.assertRaises(ValueError, memio.__setstate__, (b"closed", 0, None))
656656

657+
check_sizeof = support.check_sizeof
658+
659+
@support.cpython_only
660+
def test_sizeof(self):
661+
basesize = support.calcobjsize('P2PP2PP')
662+
check = self.check_sizeof
663+
self.assertEqual(object.__sizeof__(io.BytesIO()), basesize)
664+
check(io.BytesIO(), basesize )
665+
check(io.BytesIO(b'a'), basesize + 1 + 1 )
666+
check(io.BytesIO(b'a' * 1000), basesize + 1000 + 1 )
667+
657668

658669
class CStringIOTest(PyStringIOTest):
659670
ioclass = io.StringIO

Misc/NEWS

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -98,6 +98,9 @@ Core and Builtins
9898
Library
9999
-------
100100

101+
- Issue #15489: Add a __sizeof__ implementation for BytesIO objects.
102+
Patch by Serhiy Storchaka.
103+
101104
- Issue #15487: Add a __sizeof__ implementation for buffered I/O objects.
102105
Patch by Serhiy Storchaka.
103106

Modules/_io/bytesio.c

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -834,6 +834,17 @@ bytesio_init(bytesio *self, PyObject *args, PyObject *kwds)
834834
return 0;
835835
}
836836

837+
static PyObject *
838+
bytesio_sizeof(bytesio *self, void *unused)
839+
{
840+
Py_ssize_t res;
841+
842+
res = sizeof(bytesio);
843+
if (self->buf)
844+
res += self->buf_size;
845+
return PyLong_FromSsize_t(res);
846+
}
847+
837848
static int
838849
bytesio_traverse(bytesio *self, visitproc visit, void *arg)
839850
{
@@ -876,6 +887,7 @@ static struct PyMethodDef bytesio_methods[] = {
876887
{"truncate", (PyCFunction)bytesio_truncate, METH_VARARGS, truncate_doc},
877888
{"__getstate__", (PyCFunction)bytesio_getstate, METH_NOARGS, NULL},
878889
{"__setstate__", (PyCFunction)bytesio_setstate, METH_O, NULL},
890+
{"__sizeof__", (PyCFunction)bytesio_sizeof, METH_NOARGS, NULL},
879891
{NULL, NULL} /* sentinel */
880892
};
881893

0 commit comments

Comments
 (0)