From 7edd72db243e676514d8e036e2688fa96e573343 Mon Sep 17 00:00:00 2001 From: Ivan Smirnov Date: Thu, 20 Oct 2016 16:57:12 +0100 Subject: [PATCH] Disallow registering dtypes multiple times --- include/pybind11/numpy.h | 3 +++ tests/test_numpy_dtypes.cpp | 1 + tests/test_numpy_dtypes.py | 9 +++++++++ 3 files changed, 13 insertions(+) diff --git a/include/pybind11/numpy.h b/include/pybind11/numpy.h index dba8b7a2b..602d703cb 100644 --- a/include/pybind11/numpy.h +++ b/include/pybind11/numpy.h @@ -668,6 +668,9 @@ struct npy_format_descriptor::value>> { } static void register_dtype(std::initializer_list fields) { + if (dtype_ptr) + pybind11_fail("NumPy: dtype is already registered"); + list names, formats, offsets; for (auto field : fields) { if (!field.descr) diff --git a/tests/test_numpy_dtypes.cpp b/tests/test_numpy_dtypes.cpp index 043d41b47..f85195353 100644 --- a/tests/test_numpy_dtypes.cpp +++ b/tests/test_numpy_dtypes.cpp @@ -335,6 +335,7 @@ test_initializer numpy_dtypes([](py::module &m) { m.def("f_simple", [](SimpleStruct s) { return s.y * 10; }); m.def("f_packed", [](PackedStruct s) { return s.y * 10; }); m.def("f_nested", [](NestedStruct s) { return s.a.y * 10; }); + m.def("register_dtype", []() { PYBIND11_NUMPY_DTYPE(SimpleStruct, x, y, z); }); }); #undef PYBIND11_PACKED diff --git a/tests/test_numpy_dtypes.py b/tests/test_numpy_dtypes.py index 322400296..0503ef1a9 100644 --- a/tests/test_numpy_dtypes.py +++ b/tests/test_numpy_dtypes.py @@ -196,3 +196,12 @@ def test_scalar_conversion(): with pytest.raises(TypeError) as excinfo: func(arr[0]) assert 'incompatible function arguments' in str(excinfo.value) + + +@pytest.requires_numpy +def test_register_dtype(): + from pybind11_tests import register_dtype + + with pytest.raises(RuntimeError) as excinfo: + register_dtype() + assert 'dtype is already registered' in str(excinfo.value)