Issue #19014: memoryview.cast() is now allowed on zero-length views.
authorAntoine Pitrou <solipsis@pitrou.net>
Thu, 3 Oct 2013 17:55:41 +0000 (19:55 +0200)
committerAntoine Pitrou <solipsis@pitrou.net>
Thu, 3 Oct 2013 17:55:41 +0000 (19:55 +0200)
Lib/test/test_buffer.py
Misc/NEWS
Objects/memoryobject.c

index 747e2a287ee24ddc80787ca7dba29de14bb957a2..04e3f61e89476930b326fb444743c2ed40b25864 100644 (file)
@@ -2432,15 +2432,22 @@ class TestBufferProtocol(unittest.TestCase):
         self.assertRaises(ValueError, get_contiguous, nd[::-1], PyBUF_READ, 'C')
 
     def test_memoryview_cast_zero_shape(self):
-        # Casts are undefined if shape contains zeros. These arrays are
-        # regarded as C-contiguous by Numpy and PyBuffer_GetContiguous(),
-        # so they are not caught by the test for C-contiguity in memory_cast().
+        # Casts are undefined if buffer is multidimensional and shape
+        # contains zeros. These arrays are regarded as C-contiguous by
+        # Numpy and PyBuffer_GetContiguous(), so they are not caught by
+        # the test for C-contiguity in memory_cast().
         items = [1,2,3]
         for shape in ([0,3,3], [3,0,3], [0,3,3]):
             ex = ndarray(items, shape=shape)
             self.assertTrue(ex.c_contiguous)
             msrc = memoryview(ex)
             self.assertRaises(TypeError, msrc.cast, 'c')
+        # Monodimensional empty view can be cast (issue #19014).
+        for fmt, _, _ in iter_format(1, 'memoryview'):
+            msrc = memoryview(b'')
+            m = msrc.cast(fmt)
+            self.assertEqual(m.tobytes(), b'')
+            self.assertEqual(m.tolist(), [])
 
     def test_memoryview_struct_module(self):
 
index ad44fe7a35f6b49a315fce0dda60c899d0182bf5..794e94f3c1f6761207e7117fdc56912090e39302 100644 (file)
--- a/Misc/NEWS
+++ b/Misc/NEWS
@@ -12,6 +12,8 @@ What's New in Python 3.3.3 release candidate 1?
 Core and Builtins
 -----------------
 
+- Issue #19014: memoryview.cast() is now allowed on zero-length views.
+
 - Issue #19098: Prevent overflow in the compiler when the recursion limit is set
   absurdly high.
 
index abd069b324fe58eb564e39e87e06b997ad323610..189af88c6e619b093c5c08ab1af95afd11ca1f98 100644 (file)
@@ -1330,7 +1330,7 @@ memory_cast(PyMemoryViewObject *self, PyObject *args, PyObject *kwds)
             "memoryview: casts are restricted to C-contiguous views");
         return NULL;
     }
-    if (zero_in_shape(self)) {
+    if ((shape || self->view.ndim != 1) && zero_in_shape(self)) {
         PyErr_SetString(PyExc_TypeError,
             "memoryview: cannot cast view with zeros in shape or strides");
         return NULL;