7 #ifndef MDS_UTILS_PYTHON_CONTAINER_OPERATORS_HPP_INCLUDED 8 #define MDS_UTILS_PYTHON_CONTAINER_OPERATORS_HPP_INCLUDED 14 #include <boost/numeric/conversion/cast.hpp> 57 template<
class Derived>
78 using namespace boost;
80 Derived &
self(
static_cast<Derived&
>(*this));
82 Py_ssize_t nel(numeric_cast<Py_ssize_t>(
self.get_nel()));
84 if (PySlice_Check(idx)) {
86 Py_ssize_t start(0),stop(0),step(0),slen(0);
89 reinterpret_cast<PySliceObject*>(static_cast<PyObject*>(idx)),
90 self.get_nel(),&start,&stop,&step,&slen);
96 for (k = 0,ind = i = start;k < slen;++k,i += step,ind = i) {
97 if (ind < 0) ind += nel;
98 if (ind < 0 || ind >= nel) {
101 l.
append(
self.get_el_at(ind));
107 Py_ssize_t i = get<Py_ssize_t>(idx);
109 if (i < 0 || i >= nel) {
143 template<
class Derived>
160 using namespace boost;
162 Derived &
self(
static_cast<Derived&
>(*this));
164 Py_ssize_t nel(numeric_cast<Py_ssize_t>(
self.get_nel()));
166 if (PySlice_Check(idx)) {
168 if (!PySequence_Check(val)) {
169 throw std::invalid_argument(
"The value to be set is not a sequence");
172 Py_ssize_t start(0),stop(0),step(0),slen(0);
174 PySlice_GetIndicesEx(
175 reinterpret_cast<PySliceObject*>(static_cast<PyObject*>(idx)),
176 self.get_nel(),&start,&stop,&step,&slen);
178 Py_ssize_t len_val(PySequence_Length(val));
180 if (len_val != slen) {
181 throw std::invalid_argument(
"The rhs has not the same dimensions as the lhs.");
186 for (k = 0,ind = i = start;k < slen;++k,i += step,ind = i) {
187 if (ind < 0) ind += nel;
188 if (ind < 0 || ind >= nel) {
192 Obj py_val(PySequence_GetItem(val,k));
197 get<typename Derived::value_type>(py_val));
202 Py_ssize_t i = get<Py_ssize_t>(idx);
204 if (i < 0 || i >= nel) {
208 self.set_el_at(i,get<typename Derived::value_type>(val));
Obj py_get_item(const Obj &idx)
Manages container read access through Python indices and slices.
Contains a wrapper class for the Python list datatype.
PyObject * to_python(void)
Converts a value into a Python object.
Adds support for random access operator (i.e. square brackets) to a class that has to be exposed to t...
Main namespace of all Michele De Stefano's C++ utilities.
Adds support for random get/set access operator (i.e. square brackets) to a class that has to be expo...
Utilities and workarounds for all the extension codes.
Exception used for detecting and raising IndexError Python exceptions.
void get_ownership()
Used in place of incref, when the wrapped PyObject* was increfed already.
void py_set_item(const Obj &idx, const Obj &val)
Manages container write access through Python indices and slices.
List & append(const T &val)
Appends an element to the list.
Contains new C++ exceptions created specifically for interoperation with Python.
Utilities for converting data from/to Python.
This is a simple wrapper around the PyObject* datatype.