diff --git a/Lib/test/test_mmap.py b/Lib/test/test_mmap.py index b2a299ed172967..dff8d056aa375e 100644 --- a/Lib/test/test_mmap.py +++ b/Lib/test/test_mmap.py @@ -506,6 +506,8 @@ def test_anonymous(self): m[x] = b self.assertEqual(m[x], b) + self.assertEqual(m.size(), PAGESIZE) + def test_read_all(self): m = mmap.mmap(-1, 16) self.addCleanup(m.close) diff --git a/Misc/NEWS.d/next/Library/2025-08-28-01-29-01.gh-issue-87595.Ncgrwo.rst b/Misc/NEWS.d/next/Library/2025-08-28-01-29-01.gh-issue-87595.Ncgrwo.rst new file mode 100644 index 00000000000000..d978133992068c --- /dev/null +++ b/Misc/NEWS.d/next/Library/2025-08-28-01-29-01.gh-issue-87595.Ncgrwo.rst @@ -0,0 +1 @@ +Fix :meth:`mmap.mmap.size` method for anonymous mmap files on Unix. diff --git a/Modules/mmapmodule.c b/Modules/mmapmodule.c index 0cb4b62d734550..0ef91861d7d6e0 100644 --- a/Modules/mmapmodule.c +++ b/Modules/mmapmodule.c @@ -747,6 +747,9 @@ mmap_size_method(PyObject *op, PyObject *Py_UNUSED(ignored)) #ifdef UNIX { + if (self->trackfd && self->fd == -1) { + return PyLong_FromSsize_t(self->size); + } struct _Py_stat_struct status; if (_Py_fstat(self->fd, &status) == -1) return NULL;