Skip to content

Commit

Permalink
Merge pull request #1689 from rstudio/subset-loads-delayed-module
Browse files Browse the repository at this point in the history
`[[` loads lazy modules
  • Loading branch information
t-kalinowski authored Oct 24, 2024
2 parents 5834f6a + 9c70631 commit d524027
Show file tree
Hide file tree
Showing 3 changed files with 30 additions and 4 deletions.
2 changes: 2 additions & 0 deletions NEWS.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
# reticulate (development version)

- `[[` now loads delayed modules (#1688).

- Fixed error when attempting to use a python venv created with `uv` (#1678)

- Fixed error where `py_discover_config()` attempted to detect
Expand Down
6 changes: 4 additions & 2 deletions src/reticulate_types.h
Original file line number Diff line number Diff line change
Expand Up @@ -129,8 +129,10 @@ class PyObjectRef: public Rcpp::RObject {
SEXP xptr = Rf_findVarInFrame(get_refenv(), sym_pyobj);
if(TYPEOF(xptr) == EXTPTRSXP)
return ((PyObject*) R_ExternalPtrAddr(xptr) == NULL);
if(xptr == R_UnboundValue || xptr == R_NilValue)
return true; // return true for lazy module proxy
if(xptr == R_UnboundValue)
return false; // return false for lazy module proxy
if(xptr == R_NilValue)
return true; // ??? manually finalized obj? ??? should never happen ???
return false; // should never happen
}

Expand Down
26 changes: 24 additions & 2 deletions tests/testthat/test-delay-load.R
Original file line number Diff line number Diff line change
Expand Up @@ -20,13 +20,13 @@ test_that("imported module can be customized via delay_load", {
stopifnot(isTRUE(reticulate:::py_is_module_proxy(sys)))

print(sys)
stopifnot(isTRUE(reticulate::py_is_null_xptr(sys)))
stopifnot(isTRUE(reticulate:::py_is_module_proxy(sys)))
stopifnot(isFALSE(reticulate::py_available()))

out <- as.character(sys$byteorder)

stopifnot(isFALSE(reticulate::py_is_null_xptr(sys)))
stopifnot(isFALSE(reticulate:::py_is_module_proxy(sys)))
stopifnot(isTRUE(reticulate::py_available()))

out
})
Expand All @@ -35,3 +35,25 @@ test_that("imported module can be customized via delay_load", {
expect_true(result %in% c("little", "big"))

})


test_that("[[ loads delayed modules", {

# https://github.com/rstudio/reticulate/issues/1688
config <- py_config()
withr::local_envvar(RETICULATE_PYTHON = config$python)

result <- callr::r(function() {
time <- reticulate::import('time', delay_load = TRUE)
stopifnot(isFALSE(reticulate::py_available()))

result <- time[['time']]()
stopifnot(isTRUE(reticulate::py_available()))
result
})

# validate expected result
expect_true(typeof(result) %in% c("double", "integer"))
expect_true((result - import("time")$time()) < 10)

})

0 comments on commit d524027

Please sign in to comment.