Lenard Lindstrom added the comment:

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.

----------
nosy: +kermode
Added file: 
http://bugs.python.org/file31329/llindstrom-newbuffer-0dd8ba1c2c2c.tar.gz

_______________________________________
Python tracker <rep...@bugs.python.org>
<http://bugs.python.org/issue13797>
_______________________________________
_______________________________________________
Python-bugs-list mailing list
Unsubscribe: 
http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com

Reply via email to