Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Expose PyDict_GetItemWithError on PyDict object #2536

Merged
merged 5 commits into from Aug 6, 2022
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
47 changes: 47 additions & 0 deletions src/types/dict.rs
Expand Up @@ -156,6 +156,26 @@ impl PyDict {
}
}

/// Gets an item from the dictionary,
///
/// 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`.
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()));
}

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

/// Sets an item value.
///
/// This is equivalent to the Python statement `self[key] = value`.
Expand Down Expand Up @@ -471,6 +491,7 @@ where
#[cfg(test)]
mod tests {
use super::*;
use crate::exceptions;
#[cfg(not(PyPy))]
use crate::{types::PyList, PyTypeInfo};
use crate::{types::PyTuple, IntoPy, PyObject, PyTryFrom, Python, ToPyObject};
Expand Down Expand Up @@ -562,6 +583,32 @@ mod tests {
});
}

#[test]
fn test_get_item_with_error() {
Python::with_gil(|py| {
let mut v = HashMap::new();
v.insert(7, 32);
let ob = v.to_object(py);
let dict = <PyDict as PyTryFrom>::try_from(ob.as_ref(py)).unwrap();
assert_eq!(
32,
dict.get_item_with_error(7i32)
.unwrap()
.unwrap()
.extract::<i32>()
.unwrap()
);
assert!(dict.get_item_with_error(8i32).unwrap().is_none());

let dict_clone = dict.clone();
if let Err(err) = dict.get_item_with_error(dict_clone) {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit: use .unwrap_err() here.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done 3f1df62

assert!(err.is_instance_of::<exceptions::PyTypeError>(py));
} else {
panic!()
};
});
}

#[test]
fn test_set_item() {
Python::with_gil(|py| {
Expand Down