if (FALSE) {
# see last python exception with R traceback
reticulate::py_last_error()
# see the full R callstack from the last Python exception
reticulate::py_last_error()$r_trace$full_call
# run python code that might error,
# without modifying the user-visible python exception
safe_len <- function(x) {
last_err <- py_last_error()
tryCatch({
# this might raise a python exception if x has no `__len__` method.
import_builtins()$len(x)
}, error = function(e) {
# py_last_error() was overwritten, is now "no len method for 'object'"
py_last_error(last_err) # restore previous exception
-1L
})
}
safe_len(py_eval("object"))
}
Run the code above in your browser using DataLab