From 000aabb2a715fcea1a9857d244321bdbc2847d82 Mon Sep 17 00:00:00 2001 From: Axel Huebl Date: Tue, 11 Jun 2019 14:00:05 +0200 Subject: [PATCH] Test: Numpy Scalar Creation (#1530) I found that the numpy array tests already contained an empty-shaped array test, but none with data in it. Following PEP 3118, scalars have an empty shape and ndim 0. This works already and is now also documented/covered by a test. --- tests/test_numpy_array.cpp | 5 +++++ tests/test_numpy_array.py | 5 +++++ 2 files changed, 10 insertions(+) diff --git a/tests/test_numpy_array.cpp b/tests/test_numpy_array.cpp index 570259493..cdf0b82df 100644 --- a/tests/test_numpy_array.cpp +++ b/tests/test_numpy_array.cpp @@ -68,6 +68,9 @@ template py::handle auxiliaries(T &&r, T2 &&r2) { return l.release(); } +// note: declaration at local scope would create a dangling reference! +static int data_i = 42; + TEST_SUBMODULE(numpy_array, sm) { try { py::module::import("numpy"); } catch (...) { return; } @@ -104,6 +107,8 @@ TEST_SUBMODULE(numpy_array, sm) { // test_empty_shaped_array sm.def("make_empty_shaped_array", [] { return py::array(py::dtype("f"), {}, {}); }); + // test numpy scalars (empty shape, ndim==0) + sm.def("scalar_int", []() { return py::array(py::dtype("i"), {}, {}, &data_i); }); // test_wrap sm.def("wrap", [](py::array a) { diff --git a/tests/test_numpy_array.py b/tests/test_numpy_array.py index 8ac0e66fb..8bacb7f6d 100644 --- a/tests/test_numpy_array.py +++ b/tests/test_numpy_array.py @@ -138,6 +138,11 @@ def test_make_c_f_array(): def test_make_empty_shaped_array(): m.make_empty_shaped_array() + # empty shape means numpy scalar, PEP 3118 + assert m.scalar_int().ndim == 0 + assert m.scalar_int().shape == () + assert m.scalar_int() == 42 + def test_wrap(): def assert_references(a, b, base=None):