Skip to content

Commit

Permalink
add PyDict::get_item_with_error for PyPy
Browse files Browse the repository at this point in the history
  • Loading branch information
davidhewitt committed Jun 25, 2023
1 parent edf47b5 commit 99219b2
Show file tree
Hide file tree
Showing 3 changed files with 5 additions and 5 deletions.
1 change: 1 addition & 0 deletions newsfragments/3270.added.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Add `PyDict::get_item_with_error` on PyPy.
1 change: 1 addition & 0 deletions pyo3-ffi/src/dictobject.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ extern "C" {
pub fn PyDict_New() -> *mut PyObject;
#[cfg_attr(PyPy, link_name = "PyPyDict_GetItem")]
pub fn PyDict_GetItem(mp: *mut PyObject, key: *mut PyObject) -> *mut PyObject;
#[cfg_attr(PyPy, link_name = "PyPyDict_GetItemWithError")]
pub fn PyDict_GetItemWithError(mp: *mut PyObject, key: *mut PyObject) -> *mut PyObject;
#[cfg_attr(PyPy, link_name = "PyPyDict_SetItem")]
pub fn PyDict_SetItem(mp: *mut PyObject, key: *mut PyObject, item: *mut PyObject) -> c_int;
Expand Down
8 changes: 3 additions & 5 deletions src/types/dict.rs
Original file line number Diff line number Diff line change
Expand Up @@ -157,19 +157,17 @@ impl PyDict {
/// returns `Ok(None)` if item is not present, or `Err(PyErr)` if an error occurs.
///
/// To get a `KeyError` for non-existing keys, use `PyAny::get_item_with_error`.
#[cfg(not(PyPy))]
pub fn get_item_with_error<K>(&self, key: K) -> PyResult<Option<&PyAny>>
where
K: ToPyObject,
{
unsafe {
let ptr =
ffi::PyDict_GetItemWithError(self.as_ptr(), key.to_object(self.py()).as_ptr());
if !ffi::PyErr_Occurred().is_null() {
return Err(PyErr::fetch(self.py()));
match NonNull::new(ptr) {
Some(p) => Ok(Some(self.py().from_owned_ptr(ffi::_Py_NewRef(p.as_ptr())))),
None => PyErr::take(self.py()).map(Err).transpose(),
}

Ok(NonNull::new(ptr).map(|p| self.py().from_owned_ptr(ffi::_Py_NewRef(p.as_ptr()))))
}
}

Expand Down

0 comments on commit 99219b2

Please sign in to comment.