In Biopython (an open source library for molecular biology) we are subclassing a numpy array to add a few capabilities relevant for biology. Because our class is a subclass of a numpy array, the buffer protocol provided by the numpy array is also supported by our subclass. This is extremely useful, as it allows us to pass instances of our class to a C extension module and directly make use of the buffer protocol.
The numpy developers, however, officially discourage subclassing a numpy array, and advocate wrapping a numpy array instead. I don’t fully understand why subclassing is discouraged, but the main problem seems to be compatibility.
But a class that wraps a numpy array (i.e. instead of subclassing, the numpy array stored as an attribute) does not support the buffer protocol support, which is very inconvenient when passing the object to a C extension module.
Now if I could subclass a memoryview in the following way:
class B(memoryview):
def __new__(cls, a):
return super(B, cls).__new__(cls, a)
and create an instance as follows:
import numpy
a = numpy.array([1,2,3,4,5])
b = B(a)
then b
supports the buffer protocol by make use of the buffer protocol provided by the numpy array.
However, memoryview
does not support subclassing:
>>> class A(memoryview): pass
...
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: type 'memoryview' is not an acceptable base type
Would it be a good idea to allow subclassing a memoryview? This would enable chaining memoryviews, much in the same way buffers can be chained at the C-level.