From 16728c4da21b1444a783258ed531d8bf46eb60b2 Mon Sep 17 00:00:00 2001 From: David Hewitt <1939362+davidhewitt@users.noreply.github.com> Date: Wed, 19 Jul 2023 21:13:42 +0100 Subject: [PATCH] move PyDict::get_item_with_error to PyDict::get_item --- newsfragments/3330.changed.md | 1 + src/types/dict.rs | 42 +++++++++++++---------------------- 2 files changed, 16 insertions(+), 27 deletions(-) create mode 100644 newsfragments/3330.changed.md diff --git a/newsfragments/3330.changed.md b/newsfragments/3330.changed.md new file mode 100644 index 00000000..daa6c348 --- /dev/null +++ b/newsfragments/3330.changed.md @@ -0,0 +1 @@ +Change `PyDict::get_item` to no longer suppress arbitrary exceptions (the return type is now `PyResult>` instead of `Option<&PyAny>`), and deprecate `PyDict::get_item_with_error`. diff --git a/src/types/dict.rs b/src/types/dict.rs index 3dacae1d..8664b450 100644 --- a/src/types/dict.rs +++ b/src/types/dict.rs @@ -132,35 +132,10 @@ impl PyDict { /// Gets an item from the dictionary. /// - /// Returns `None` if the item is not present, or if an error occurs. + /// Returns `Ok(None)` if the item is not present. /// /// To get a `KeyError` for non-existing keys, use `PyAny::get_item`. - pub fn get_item(&self, key: K) -> Option<&PyAny> - where - K: ToPyObject, - { - fn inner(dict: &PyDict, key: PyObject) -> Option<&PyAny> { - let py = dict.py(); - // PyDict_GetItem returns a borrowed ptr, must make it owned for safety (see #890). - // PyObject::from_borrowed_ptr_or_opt will take ownership in this way. - unsafe { - PyObject::from_borrowed_ptr_or_opt( - py, - ffi::PyDict_GetItem(dict.as_ptr(), key.as_ptr()), - ) - } - .map(|pyobject| pyobject.into_ref(py)) - } - - inner(self, key.to_object(self.py())) - } - - /// 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(&self, key: K) -> PyResult> + pub fn get_item(&self, key: K) -> PyResult> where K: ToPyObject, { @@ -182,6 +157,19 @@ impl PyDict { inner(self, key.to_object(self.py())) } + /// Deprecated version of `get_item`. + #[deprecated( + since = "0.20.0", + note = "this is now equivalent to `PyDict::get_item`" + )] + #[inline] + pub fn get_item_with_error(&self, key: K) -> PyResult> + where + K: ToPyObject, + { + self.get_item(key) + } + /// Sets an item value. /// /// This is equivalent to the Python statement `self[key] = value`.