Skip to content

Commit 16379de

Browse files
committed
apacheGH-38626: [Python] Fix segfault when PyArrow is imported at shutdown
Some C++ destructors may be called after the Python interpreter has ceased to exist.
1 parent e62ec62 commit 16379de

File tree

2 files changed

+23
-7
lines changed

2 files changed

+23
-7
lines changed

python/pyarrow/src/arrow/python/common.h

+10-7
Original file line numberDiff line numberDiff line change
@@ -188,7 +188,12 @@ class ARROW_PYTHON_EXPORT OwnedRef {
188188
return *this;
189189
}
190190

191-
~OwnedRef() { reset(); }
191+
~OwnedRef() {
192+
// GH-38626: destructor may be called after the Python interpreter is finalized.
193+
if (Py_IsInitialized()) {
194+
reset();
195+
}
196+
}
192197

193198
void reset(PyObject* obj) {
194199
Py_XDECREF(obj_);
@@ -225,13 +230,11 @@ class ARROW_PYTHON_EXPORT OwnedRefNoGIL : public OwnedRef {
225230
explicit OwnedRefNoGIL(PyObject* obj) : OwnedRef(obj) {}
226231

227232
~OwnedRefNoGIL() {
228-
// This destructor may be called after the Python interpreter is finalized.
229-
// At least avoid spurious attempts to take the GIL when not necessary.
230-
if (obj() == NULLPTR) {
231-
return;
233+
// GH-38626: destructor may be called after the Python interpreter is finalized.
234+
if (Py_IsInitialized() && obj() != NULLPTR) {
235+
PyAcquireGIL lock;
236+
reset();
232237
}
233-
PyAcquireGIL lock;
234-
reset();
235238
}
236239
};
237240

python/pyarrow/tests/test_misc.py

+13
Original file line numberDiff line numberDiff line change
@@ -117,6 +117,19 @@ def test_runtime_info():
117117
subprocess.check_call([sys.executable, "-c", code], env=env)
118118

119119

120+
def test_import_at_shutdown():
121+
# GH-38626: importing PyArrow at interpreter shutdown would crash
122+
code = """if 1:
123+
import atexit
124+
125+
def import_arrow():
126+
import pyarrow
127+
128+
atexit.register(import_arrow)
129+
"""
130+
subprocess.check_call([sys.executable, "-c", code])
131+
132+
120133
@pytest.mark.skipif(sys.platform == "win32",
121134
reason="Path to timezone database is not configurable "
122135
"on non-Windows platforms")

0 commit comments

Comments
 (0)