Python 3.8 added the memoryview.toreadonly() method. But is there a way to make a read-only memoryview in previous version of python -- specifically Python 3.5 and 3.3?
For a little bit more background, I use memoryviews to share parts of large binary blobs between objects. Sometimes the blob is an in-memory byte object, but sometimes it is also a read/write mmapped file. And I would like to avoid modifications by mistake of the underlying file through the memoryviews.
You can create a read-only wrapper/proxy class for
memoryviewto deny setter and deleter calls. For getter calls, make sure to wrap the sliced view in another instance of the read-only proxy class if a slice is requested:so that:
outputs:
and produces:
Demo of the code running on Python 2.7: https://ideone.com/2iivHt