diff --git a/src/python/histogram.cpp b/src/python/histogram.cpp index 57b0589f..34c66824 100644 --- a/src/python/histogram.cpp +++ b/src/python/histogram.cpp @@ -38,6 +38,11 @@ struct axis_visitor : public static_visitor python::object histogram_axis(const dynamic_histogram<>& self, unsigned i) { + if (i < 0) i += self.dim(); + if (i < 0 || i >= self.dim()) { + PyErr_SetString(PyExc_IndexError, "axis index out of range"); + python::throw_error_already_set(); + } return apply_visitor(axis_visitor(), self.axis(i)); } @@ -275,6 +280,13 @@ struct storage_access { return python::object(); } + if (!b.ptr_) { + // PyErr_SetString(PyExc_KeyError, "cannot convert empty histogram"); + // python::throw_error_already_set(); + // workaround: for some reason, exception is ignored here + return python::object(); + } + python::dict d; python::list shapes; python::list strides; @@ -318,8 +330,8 @@ void register_histogram() .def(init&>()) .add_property("__array_interface__", &storage_access::array_interface) - .add_property("dim", &dynamic_histogram<>::dim, - "dimensions of the histogram (number of axes)") + .def("__len__", &dynamic_histogram<>::dim) + .def("__getitem__", histogram_axis) .def("axis", histogram_axis, ":param int i: index of the axis\n" ":returns: axis object for axis i", diff --git a/test/python_suite_test.py.in b/test/python_suite_test.py.in index 956db150..80cd37bd 100755 --- a/test/python_suite_test.py.in +++ b/test/python_suite_test.py.in @@ -327,7 +327,7 @@ class histogramtest(unittest.TestCase): histogram(integer_axis(-1, 1), unknown_keyword="nh") h = histogram(integer_axis(-1, 1)) - self.assertEqual(h.dim, 1) + self.assertEqual(len(h), 1) self.assertEqual(h.axis(0), integer_axis(-1, 1)) self.assertEqual(h.axis(0).shape, 5) self.assertEqual(histogram(integer_axis(-1, 1, uoflow=False)).axis(0).shape, 3) @@ -522,7 +522,7 @@ class histogramtest(unittest.TestCase): io.seek(0) b = pickle.load(io) self.assertNotEqual(id(a), id(b)) - self.assertEqual(a.dim, b.dim) + self.assertEqual(len(a), len(b)) self.assertEqual(a.axis(0), b.axis(0)) self.assertEqual(a.axis(1), b.axis(1)) self.assertEqual(a.axis(2), b.axis(2)) @@ -550,7 +550,7 @@ class histogramtest(unittest.TestCase): io.seek(0) b = pickle.load(io) self.assertNotEqual(id(a), id(b)) - self.assertEqual(a.dim, b.dim) + self.assertEqual(len(a), len(b)) self.assertEqual(a.axis(0), b.axis(0)) self.assertEqual(a.axis(1), b.axis(1)) self.assertEqual(a.axis(2), b.axis(2))