Skip to content

Commit c90c396

Browse files
committed
bpo-43429: mmap.size() now returns the size on Unix for anonymous memory
Previously, the size would be returned on Windows and an OSError would be raised on Unix.
1 parent ff5f059 commit c90c396

File tree

5 files changed

+19
-0
lines changed

5 files changed

+19
-0
lines changed

Doc/library/mmap.rst

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -281,6 +281,11 @@ To map anonymous memory, -1 should be passed as the fileno along with the length
281281
Return the length of the file, which can be larger than the size of the
282282
memory-mapped area.
283283

284+
.. versionchanged:: 3.10
285+
For a mapping of anonymous memory, the size is now returned on both
286+
Unix and Windows. Previously, the size would be returned on Windows
287+
and an :exc:`OSError` would be raised on Unix.
288+
284289

285290
.. method:: tell()
286291

Doc/whatsnew/3.10.rst

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1098,6 +1098,12 @@ Changes in the Python API
10981098
also inherits the current builtins.
10991099
(Contributed by Victor Stinner in :issue:`42990`.)
11001100
1101+
* The :meth:`~mmap.mmap.size` method of the :class:`mmap.mmap` class
1102+
now returns the size of an anonymous mapping on both Unix and Windows.
1103+
Previously, the size would be returned on Windows and an :exc:`OSError` would
1104+
be raised on Unix.
1105+
(Contributed by Zackery Spytz in :issue:`43429`.)
1106+
11011107
CPython bytecode changes
11021108
========================
11031109

Lib/test/test_mmap.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -405,6 +405,7 @@ def test_anonymous(self):
405405
b = x & 0xff
406406
m[x] = b
407407
self.assertEqual(m[x], b)
408+
self.assertEqual(m.size(), PAGESIZE)
408409

409410
def test_read_all(self):
410411
m = mmap.mmap(-1, 16)
Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
The :meth:`~mmap.mmap.size` method of the :class:`mmap.mmap` class now
2+
returns the size of an anonymous mapping on both Unix and Windows.
3+
Previously, the size would be returned on Windows and an :exc:`OSError`
4+
would be raised on Unix.

Modules/mmapmodule.c

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -458,6 +458,9 @@ mmap_size_method(mmap_object *self,
458458

459459
#ifdef UNIX
460460
{
461+
if (self->fd == -1) {
462+
return PyLong_FromSsize_t(self->size);
463+
}
461464
struct _Py_stat_struct status;
462465
if (_Py_fstat(self->fd, &status) == -1)
463466
return NULL;

0 commit comments

Comments
 (0)