This issue tracker has been migrated to GitHub, and is currently read-only.
For more information, see the GitHub FAQs in the Python's Developer Guide.

Author kermode
Recipients Arfrever, Jacob.Holm, alex, eric.snow, kermode, mark.dickinson, ncoghlan, pitrou, rhettinger, sbt, scoder, skrah
Date 2013-08-16.22:53:36
SpamBayes Score -1.0
Marked as misclassified Yes
Message-id <1376693616.56.0.00933742700547.issue13797@psf.upfronthosting.co.za>
In-reply-to
Content
A fourth way to add __getbuffer__ and __releasebuffer__ special methods to a Python class is through a new base class/mixin. The Py_buffer struct pointer passed to __getbuffer__ and __releasebuffer__ is wrapped with another special object type, which exposes the C struct fields as attributes. The base class is a direct subclass of object. Both the base and wrapper classes are implemented in an extension module. 

The use case is unit testing. A memoryview object may be adequate for simple C-contiguous arrays, but fails with F-contiguous or any non-contiguous array. It cannot export any arbitrary view, especially a deliberately invalid view, useful for testing error handlers.

My implementation is at https://bitbucket.org/llindstrom/newbuffer . It is used in Pygame 1.9.2 unit tests: https://bitbucket.org/pygame/pygame . The newbuffer module exports two classes, BufferMixin and Py_buffer. The BufferMixin class adds bf_getbuffer and bf_releasebuffer slot functions to base class PyObject, nothing more. The Py_buffer class is low level, exposing pointer fields as integer addresses. It is designed for use with ctypes and is modelled on ctypes.Structure.

Some limitations. In a class declaration, BufferMixin must be first in the inheritance list for the subclass to inherit the PEP 3118 interface. A buffer interface cannot be added to a builtin.

I suggest this is a practical alternative to the three previously proposed solutions to this issue. This option takes its precedence from the ctypes module, which adds dangerous memory level access to Python, but optionally. It does not require modification of the base code, only an addition to the standard library. Finally, this approach has been demonstrated in a real-world application.
History
Date User Action Args
2013-08-16 22:53:36kermodesetrecipients: + kermode, rhettinger, mark.dickinson, ncoghlan, pitrou, scoder, Arfrever, alex, skrah, sbt, eric.snow, Jacob.Holm
2013-08-16 22:53:36kermodesetmessageid: <1376693616.56.0.00933742700547.issue13797@psf.upfronthosting.co.za>
2013-08-16 22:53:36kermodelinkissue13797 messages
2013-08-16 22:53:36kermodecreate