Skip to content

Commit

Permalink
fix coerce in py_slice()
Browse files Browse the repository at this point in the history
  • Loading branch information
t-kalinowski committed Mar 7, 2025
1 parent b7617db commit dd6c8de
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 9 deletions.
28 changes: 20 additions & 8 deletions src/python.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -4619,22 +4619,34 @@ PyObjectRef py_capsule(SEXP x) {
PyObjectRef py_slice(SEXP start = R_NilValue, SEXP stop = R_NilValue, SEXP step = R_NilValue) {
GILScope _gil;

PyObjectPtr start_, stop_, step_;
auto coerce_slice_arg = [](SEXP x) -> PyObject* {
if (x == R_NilValue) {
return NULL;
}
if (TYPEOF(x) == INTSXP || TYPEOF(x) == REALSXP) {
return PyLong_FromLong(Rf_asInteger(x));
}
if (is_py_object(x)) {
PyObject* pyobj = PyObjectRef(x, false).get();
Py_IncRef(pyobj);
return pyobj;
}
return r_to_py(x, false);
};

if (start != R_NilValue)
start_.assign(PyLong_FromLong(Rf_asInteger(start)));
if (stop != R_NilValue)
stop_.assign(PyLong_FromLong(Rf_asInteger(stop)));
if (step != R_NilValue)
step_.assign(PyLong_FromLong(Rf_asInteger(step)));
PyObjectPtr start_(coerce_slice_arg(start));
PyObjectPtr stop_(coerce_slice_arg(stop));
PyObjectPtr step_(coerce_slice_arg(step));

PyObject* out(PySlice_New(start_, stop_, step_));
PyObject* out = PySlice_New(start_, stop_, step_);
if (out == NULL)
throw PythonException(py_fetch_error());

return py_ref(out, false);
}



//' @rdname iterate
//' @export
// [[Rcpp::export]]
Expand Down
2 changes: 1 addition & 1 deletion tests/testthat/test-python-base-r-generics.R
Original file line number Diff line number Diff line change
Expand Up @@ -173,7 +173,7 @@ test_that("[ can infer slices, multiple args", {

test_that("[ passes through python objects", {

skip_if_no_numpy("numpy")
skip_if_no_numpy()

np <- import("numpy", convert = FALSE)

Expand Down

0 comments on commit dd6c8de

Please sign in to comment.