Skip to content

mmap

Memory-mapped file view utilities.

This module provides :func:file_view which creates a read-only memory-mapped view of a file, exposing it as a memoryview for efficient access without loading the entire file into process memory.

file_view(path)

Create a read-only memory-mapped view of a file.

Parameters:

Name Type Description Default
path

Filesystem path to the file to memory-map.

required

Returns:

Type Description

A memoryview over the memory-mapped file contents. The underlying mmap

object is kept alive by the memoryview's buffer protocol and is released

when the memoryview is garbage collected.

Example
import os
import tempfile

fd, path = tempfile.mkstemp()
os.write(fd, b'x' * 1024)
os.close(fd)

view = mmap.file_view(path)  # read-only view over the file contents
header = bytes(view[:16])
Source code in py_misc_utils/mmap.py
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
def file_view(path):
  """Create a read-only memory-mapped view of a file.

  Args:
    path: Filesystem path to the file to memory-map.

  Returns:
    A memoryview over the memory-mapped file contents. The underlying mmap
    object is kept alive by the memoryview's buffer protocol and is released
    when the memoryview is garbage collected.

  Example:
    import os
    import tempfile

    fd, path = tempfile.mkstemp()
    os.write(fd, b'x' * 1024)
    os.close(fd)

    view = mmap.file_view(path)  # read-only view over the file contents
    header = bytes(view[:16])
  """
  with osfd.OsFd(path, os.O_RDONLY) as fd:
    mm = mmap.mmap(fd, 0, access=mmap.ACCESS_READ)

  # We can close the fd, but we cannot close the mmap. When the memoryview
  # will be garbage collected, the buffer protocol used by memoryview will
  # decref the mmap object which will be automatically released.
  return memoryview(mm)