Skip to content

Commit

Permalink
Merge pull request #1664 from rstudio/fix-finalizer-segfault
Browse files Browse the repository at this point in the history
Fix finalizer segfault
  • Loading branch information
t-kalinowski committed Sep 9, 2024
2 parents 1fc95e6 + 8b3723c commit 8c0c5ee
Show file tree
Hide file tree
Showing 3 changed files with 16 additions and 7 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)

- Fixed segfault encountered when running Python finalizer (#1663, #1664)

# reticulate 1.39.0

- Python background threads can now run in parallel with the R session (#1641).
Expand Down
4 changes: 3 additions & 1 deletion R/package.R
Original file line number Diff line number Diff line change
Expand Up @@ -224,7 +224,9 @@ initialize_python <- function(required_module = NULL, use_environment = NULL) {

)

reg.finalizer(.globals, function(e) py_finalize(), onexit = TRUE)
# allow disabling the Python finalizer
if (!tolower(Sys.getenv("RETICULATE_DISABLE_PYTHON_FINALIZER")) %in% c("true", "1", "yes"))
reg.finalizer(.globals, function(e) py_finalize(), onexit = TRUE)

# set available flag indicating we have py bindings
config$available <- TRUE
Expand Down
17 changes: 11 additions & 6 deletions src/python.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1167,7 +1167,7 @@ PyObject* pandas_arrays () {
}

bool is_pandas_na_like(PyObject* x) {
const static PyObjectPtr np_nan(PyObject_GetAttrString(numpy(), "nan"));
const static PyObject* np_nan = PyObject_GetAttrString(numpy(), "nan");
return is_pandas_na(x) || (x == Py_None) || (x == (PyObject*)np_nan);
}

Expand Down Expand Up @@ -1203,11 +1203,16 @@ bool py_is_callable(PyObjectRef x) {

// caches np.nditer function so we don't need to obtain it everytime we want to
// cast numpy string arrays into R objects.
PyObject* get_np_nditer () {
const static PyObjectPtr np_nditer(PyObject_GetAttrString(numpy(), "nditer"));
if (np_nditer.is_null()) {
throw PythonException(py_fetch_error());
}
PyObject* get_np_nditer() {
static PyObject* np_nditer = []() -> PyObject* {
PyObject* np_nditer = PyObject_GetAttrString(numpy(), "nditer");
if (np_nditer == NULL) {
throw PythonException(py_fetch_error());
}
return np_nditer;
}();

// Return the static np_nditer
return np_nditer;
}

Expand Down

0 comments on commit 8c0c5ee

Please sign in to comment.