Skip to content

Commit

Permalink
Don't use PyList.get_item_unchecked() on free-threaded build (#4539)
Browse files Browse the repository at this point in the history
* disable list.get_item_unchecked() on the free-threaded build

* add changelog entry
  • Loading branch information
ngoldbaum authored Sep 30, 2024
1 parent 116170a commit ce18f79
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 5 deletions.
3 changes: 3 additions & 0 deletions newsfragments/4539.removed.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
* `PyListMethods::get_item_unchecked` is disabled on the free-threaded build.
It relies on accessing list internals without any locking and is not
thread-safe without the GIL to synchronize access.
10 changes: 5 additions & 5 deletions src/types/list.rs
Original file line number Diff line number Diff line change
Expand Up @@ -182,7 +182,7 @@ pub trait PyListMethods<'py>: crate::sealed::Sealed {
/// # Safety
///
/// Caller must verify that the index is within the bounds of the list.
#[cfg(not(Py_LIMITED_API))]
#[cfg(not(any(Py_LIMITED_API, Py_GIL_DISABLED)))]
unsafe fn get_item_unchecked(&self, index: usize) -> Bound<'py, PyAny>;

/// Takes the slice `self[low:high]` and returns it as a new list.
Expand Down Expand Up @@ -305,7 +305,7 @@ impl<'py> PyListMethods<'py> for Bound<'py, PyList> {
/// # Safety
///
/// Caller must verify that the index is within the bounds of the list.
#[cfg(not(Py_LIMITED_API))]
#[cfg(not(any(Py_LIMITED_API, Py_GIL_DISABLED)))]
unsafe fn get_item_unchecked(&self, index: usize) -> Bound<'py, PyAny> {
// PyList_GET_ITEM return borrowed ptr; must make owned for safety (see #890).
ffi::PyList_GET_ITEM(self.as_ptr(), index as Py_ssize_t)
Expand Down Expand Up @@ -496,9 +496,9 @@ impl<'py> BoundListIterator<'py> {
}

unsafe fn get_item(&self, index: usize) -> Bound<'py, PyAny> {
#[cfg(any(Py_LIMITED_API, PyPy))]
#[cfg(any(Py_LIMITED_API, PyPy, Py_GIL_DISABLED))]
let item = self.list.get_item(index).expect("list.get failed");
#[cfg(not(any(Py_LIMITED_API, PyPy)))]
#[cfg(not(any(Py_LIMITED_API, PyPy, Py_GIL_DISABLED)))]
let item = self.list.get_item_unchecked(index);
item
}
Expand Down Expand Up @@ -893,7 +893,7 @@ mod tests {
});
}

#[cfg(not(any(Py_LIMITED_API, PyPy)))]
#[cfg(not(any(Py_LIMITED_API, PyPy, Py_GIL_DISABLED)))]
#[test]
fn test_list_get_item_unchecked_sanity() {
Python::with_gil(|py| {
Expand Down

0 comments on commit ce18f79

Please sign in to comment.