Buffers and Memoryview Objects explained for the non-C programmer

Viewed 4884

Python 2.7 has introduced a new API for buffers and memoryview objects.

I read the documentation on them and I think I got the basic concept (accessing the internal data of an object in a raw form without copying it, which I suppose means a "faster and less memory-hungry" way to get object data), but to really understand the documentation, the reader should have a knowledge of C that is beyond the one I have.

I would be very grateful if somebody would take the time to:

  • explain buffers and memoryview objects in "layman terms" and
  • describe a scenario in which using buffers and memoryview objects would be "the Pythonic way" of doing things
2 Answers

Part of the answer I was looking for is that buffer is the "old way", that memoryview is the new way, but was backported to 2.7 - see the archived blog here

This doesn't answer my question of why the C API I thought I implemented in 2.7 lets me construct a buffer but not a memoryview...

To get memoryview to work in Python 2.7, you need to have the Py_TPFLAGS_HAVE_NEWBUFFER flag set in tp_flags. I found that the built-in bytearray source was a good reference; it is in Include/bytearrayobject.h and Objects/bytearrayobject.c.

Related