[Numpy-discussion] "expected a single-segment buffer object"

Anne Archibald peridot.faceted at gmail.com
Wed Jul 9 19:55:10 EDT 2008


Hi,

When trying to construct an ndarray, I sometimes run into the
more-or-less mystifying error "expected a single-segment buffer
object":

Out[54]: (0, 16, 8)
In [55]: A=np.zeros(2); A=A[np.newaxis,...];
np.ndarray(strides=A.strides,shape=A.shape,buffer=A,dtype=A.dtype)
---------------------------------------------------------------------------
<type 'exceptions.TypeError'>             Traceback (most recent call last)

/home/peridot/<ipython console> in <module>()

<type 'exceptions.TypeError'>: expected a single-segment buffer object

In [56]: A.strides
Out[56]: (0, 8)

That is, when I try to construct an ndarray based on an array with a
zero stride, I get this mystifying error. Zero-strided arrays appear
naturally when one uses newaxis, but they are valuable in their own
right (for example for broadcasting purposes). So it's a bit awkward
to have this error appearing when one tries to feed them to
ndarray.__new__ as a buffer. I can, I think, work around it by
removing all axes with stride zero:

def bufferize(A):
   idx = []
   for v in A.strides:
       if v==0:
           idx.append(0)
       else:
           idx.append(slice(None,None,None))
   return A[tuple(idx)]

Is there any reason for this restriction?

Thanks,
Anne



More information about the NumPy-Discussion mailing list