An mmap view has its own lifetime and access mode; closing the map does not close the source file.
Make this comfortable
Python mmap access modes: write-through changes a file, copy-on-write does not
Operation contract
A temporary receipt file begins in the hold state. A writable map changes four status bytes to paid and flushes them. A later copy-on-write map changes the same bytes only in its private view. Reading the file afterward still returns paid.
Failure boundary
An empty file cannot be mapped with this fixed-length fixture. A sliced flush can require page-aligned offsets, so this program flushes the whole mapping. Flush and close do not establish power-loss durability; applications requiring it need a platform-aware filesystem sync and recovery design.
Working program
import mmap
from pathlib import Path
from tempfile import TemporaryDirectory
with TemporaryDirectory() as directory:
receipt_path = Path(directory) / "receipt-47.state"
receipt_path.write_bytes(b"R-0047:hold")
with receipt_path.open("r+b") as receipt_file:
with mmap.mmap(receipt_file.fileno(), 0, access=mmap.ACCESS_WRITE) as view:
view[7:11] = b"paid"
view.flush()
with mmap.mmap(receipt_file.fileno(), 0, access=mmap.ACCESS_COPY) as private_view:
private_view[7:11] = b"void"
print("private", bytes(private_view[:]))
print("stored", receipt_path.read_bytes())Output
private b'R-0047:void'
stored b'R-0047:paid'Costs and limits
Mapping uses virtual address space proportional to the mapped region; pages are loaded as accessed. A full flush may touch many dirty pages. It is not automatically faster than a small ordinary file write.
Common Mistakes
- ACCESS_COPY edits are not persisted to the source file.
- Closing a map does not close the file object that provided its descriptor.
- A successful flush is not a cross-platform crash-durability promise.
Connected lessons
python
mmap-write-vs-copy
