Last active
June 4, 2022 18:12
-
-
Save xflr6/f70aedb1ee274ae9410b to your computer and use it in GitHub Desktop.
More convenient context manager for mmap.mmap
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
"""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