Skip to content

Commit 314c942

Browse files
committed
Specify error message on non-contiguous numpy array
1 parent d06b1dc commit 314c942

2 files changed

Lines changed: 25 additions & 9 deletions

File tree

src/serialize/serializer.rs

Lines changed: 12 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -330,14 +330,18 @@ impl<'p> Serialize for PyObjectSerializer {
330330
Ok(val) => val.serialize(serializer),
331331
Err(PyArrayError::Malformed) => err!("numpy array is malformed"),
332332
Err(PyArrayError::NotContiguous) | Err(PyArrayError::UnsupportedDataType) => {
333-
DefaultSerializer::new(
334-
self.ptr,
335-
self.opts,
336-
self.default_calls,
337-
self.recursion,
338-
self.default,
339-
)
340-
.serialize(serializer)
333+
if self.default.is_none() {
334+
err!("numpy array is not C contiguous; use ndarray.tolist() in default")
335+
} else {
336+
DefaultSerializer::new(
337+
self.ptr,
338+
self.opts,
339+
self.default_calls,
340+
self.recursion,
341+
self.default,
342+
)
343+
.serialize(serializer)
344+
}
341345
}
342346
},
343347
ObType::NumpyScalar => NumpyScalar::new(self.ptr).serialize(serializer),

test/test_numpy.py

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -182,7 +182,7 @@ def test_numpy_array_d3_f64(self):
182182
b"[[[1.0,2.0],[3.0,4.0]],[[5.0,6.0],[7.0,8.0]]]",
183183
)
184184

185-
def test_numpy_array_fotran(self):
185+
def test_numpy_array_fortran(self):
186186
array = numpy.array([[1, 2], [3, 4]], order="F")
187187
assert array.flags["F_CONTIGUOUS"] == True
188188
with self.assertRaises(orjson.JSONEncodeError):
@@ -194,6 +194,18 @@ def test_numpy_array_fotran(self):
194194
orjson.dumps(array.tolist()),
195195
)
196196

197+
def test_numpy_array_non_contiguous_message(self):
198+
array = numpy.array([[1, 2], [3, 4]], order="F")
199+
assert array.flags["F_CONTIGUOUS"] == True
200+
try:
201+
orjson.dumps(array, option=orjson.OPT_SERIALIZE_NUMPY)
202+
assert False
203+
except TypeError as exc:
204+
self.assertEqual(
205+
str(exc),
206+
"numpy array is not C contiguous; use ndarray.tolist() in default",
207+
)
208+
197209
def test_numpy_array_unsupported_dtype(self):
198210
array = numpy.array([[1, 2], [3, 4]], numpy.float16)
199211
with self.assertRaises(orjson.JSONEncodeError):

0 commit comments

Comments
 (0)