diff options
Diffstat (limited to 'numpy')
-rw-r--r-- | numpy/core/src/multiarray/arraytypes.c.src | 12 | ||||
-rw-r--r-- | numpy/core/tests/test_multiarray.py | 42 |
2 files changed, 52 insertions, 2 deletions
diff --git a/numpy/core/src/multiarray/arraytypes.c.src b/numpy/core/src/multiarray/arraytypes.c.src index 8a82ff53e..abe3d749d 100644 --- a/numpy/core/src/multiarray/arraytypes.c.src +++ b/numpy/core/src/multiarray/arraytypes.c.src @@ -2297,9 +2297,13 @@ STRING_nonzero (char *ip, PyArrayObject *ap) int len = PyArray_DESCR(ap)->elsize; int i; npy_bool nonz = NPY_FALSE; + npy_bool seen_null = NPY_FALSE; for (i = 0; i < len; i++) { - if (!Py_STRING_ISSPACE(*ip)) { + if (*ip == '\0') { + seen_null = NPY_TRUE; + } + else if (seen_null || !Py_STRING_ISSPACE(*ip)) { nonz = NPY_TRUE; break; } @@ -2320,6 +2324,7 @@ UNICODE_nonzero (npy_ucs4 *ip, PyArrayObject *ap) int len = PyArray_DESCR(ap)->elsize >> 2; int i; npy_bool nonz = NPY_FALSE; + npy_bool seen_null = NPY_FALSE; char *buffer = NULL; if ((!PyArray_ISNOTSWAPPED(ap)) || (!PyArray_ISALIGNED(ap))) { @@ -2335,7 +2340,10 @@ UNICODE_nonzero (npy_ucs4 *ip, PyArrayObject *ap) } for (i = 0; i < len; i++) { - if (!PyArray_UCS4_ISSPACE(*ip)) { + if (*ip == '\0') { + seen_null = NPY_TRUE; + } + else if (seen_null || !PyArray_UCS4_ISSPACE(*ip)) { nonz = NPY_TRUE; break; } diff --git a/numpy/core/tests/test_multiarray.py b/numpy/core/tests/test_multiarray.py index e6911d0e3..6f45972c3 100644 --- a/numpy/core/tests/test_multiarray.py +++ b/numpy/core/tests/test_multiarray.py @@ -5731,5 +5731,47 @@ class TestArrayPriority(TestCase): assert_(isinstance(f(b, a), self.Other), msg) +class TestBytestringArrayNonzero(TestCase): + + def test_empty_bstring_array_is_falsey(self): + self.assertFalse(np.array([''], dtype=np.str)) + + def test_whitespace_bstring_array_is_falsey(self): + a = np.array(['spam'], dtype=np.str) + a[0] = ' \0\0' + self.assertFalse(a) + + def test_all_null_bstring_array_is_falsey(self): + a = np.array(['spam'], dtype=np.str) + a[0] = '\0\0\0\0' + self.assertFalse(a) + + def test_null_inside_bstring_array_is_truthy(self): + a = np.array(['spam'], dtype=np.str) + a[0] = ' \0 \0' + self.assertTrue(a) + + +class TestUnicodeArrayNonzero(TestCase): + + def test_empty_ustring_array_is_falsey(self): + self.assertFalse(np.array([''], dtype=np.unicode)) + + def test_whitespace_ustring_array_is_falsey(self): + a = np.array(['eggs'], dtype=np.unicode) + a[0] = ' \0\0' + self.assertFalse(a) + + def test_all_null_ustring_array_is_falsey(self): + a = np.array(['eggs'], dtype=np.unicode) + a[0] = '\0\0\0\0' + self.assertFalse(a) + + def test_null_inside_ustring_array_is_truthy(self): + a = np.array(['eggs'], dtype=np.unicode) + a[0] = ' \0 \0' + self.assertTrue(a) + + if __name__ == "__main__": run_module_suite() |