Skip to content

gh-87595: mmap.size() now returns the size on Unix for anonymous memory #24781

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 4 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions Doc/library/mmap.rst
Original file line number Diff line number Diff line change
Expand Up @@ -291,6 +291,11 @@ To map anonymous memory, -1 should be passed as the fileno along with the length
Return the length of the file, which can be larger than the size of the
memory-mapped area.

.. versionchanged:: 3.11
For a mapping of anonymous memory, the size is now returned on both
Unix and Windows. Previously, the size would be returned on Windows
and an :exc:`OSError` would be raised on Unix.


.. method:: tell()

Expand Down
9 changes: 9 additions & 0 deletions Doc/whatsnew/3.12.rst
Original file line number Diff line number Diff line change
Expand Up @@ -426,6 +426,15 @@ math
* Added :func:`math.sumprod` for computing a sum of products.
(Contributed by Raymond Hettinger in :gh:`100485`.)

mmap
----

* The :meth:`~mmap.mmap.size` method of the :class:`mmap.mmap` class
now returns the size of an anonymous mapping on both Unix and Windows.
Previously, the size would be returned on Windows and an :exc:`OSError` would
be raised on Unix.
(Contributed by Zackery Spytz in :issue:`43429`.)

os
--

Expand Down
1 change: 1 addition & 0 deletions Lib/test/test_mmap.py
Original file line number Diff line number Diff line change
Expand Up @@ -419,6 +419,7 @@ def test_anonymous(self):
b = x & 0xff
m[x] = b
self.assertEqual(m[x], b)
self.assertEqual(m.size(), PAGESIZE)

def test_read_all(self):
m = mmap.mmap(-1, 16)
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
The :meth:`~mmap.mmap.size` method of the :class:`mmap.mmap` class now
returns the size of an anonymous mapping on both Unix and Windows.
Previously, the size would be returned on Windows and an :exc:`OSError`
would be raised on Unix.
3 changes: 3 additions & 0 deletions Modules/mmapmodule.c
Original file line number Diff line number Diff line change
Expand Up @@ -459,6 +459,9 @@ mmap_size_method(mmap_object *self,

#ifdef UNIX
{
if (self->fd == -1) {
return PyLong_FromSsize_t(self->size);
}
struct _Py_stat_struct status;
if (_Py_fstat(self->fd, &status) == -1)
return NULL;
Expand Down