Skip to content

Instantly share code, notes, and snippets.

@xflr6
Last active June 4, 2022 18:12
Show Gist options
  • Save xflr6/f70aedb1ee274ae9410b to your computer and use it in GitHub Desktop.
Save xflr6/f70aedb1ee274ae9410b to your computer and use it in GitHub Desktop.
More convenient context manager for mmap.mmap
"""More convenient context manager for mmap.mmap."""
from collections.abc import Iterator
import contextlib
import mmap
import os
@contextlib.contextmanager
def memorymapped_compat(path: os.PathLike | str) -> Iterator[mmap.mmap]:
"""Return a block context with `path` as memory-mapped file."""
f = open(path, 'rb')
try:
m = mmap.mmap(f.fileno(), 0, access=mmap.ACCESS_READ)
try:
yield m
finally:
m.close()
finally:
f.close()
@contextlib.contextmanager
def memorymapped(path: os.PathLike | str)-> Iterator[mmap.mmap]:
"""Return a block context with `path` as memory-mapped file."""
access = mmap.ACCESS_READ
with open(path, 'rb') as f, mmap.mmap(f.fileno(), 0, access=access) as m:
yield m
if __name__ == '__main__':
for func in(memorymapped_compat, memorymapped):
print(func)
with func('memorymapped.py') as data:
print(data[250:307])
print()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment