bpo-33176: Add a toreadonly() method to memoryviews. by pitrou · Pull Request #6466 · python/cpython

{
CHECK_RELEASED(self);
if (self->view.readonly) {
Py_INCREF(self);

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think we always need to use mbuf_add_view because of the release() thingy:

>>> b = bytes(10)
>>> m = memoryview(b)
>>> with m.toreadonly() as x:
...     pass
... 
>>> m[0]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: operation forbidden on released memoryview object

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for catching this. It's indeed necessary to create a new object.