Skip to content

Commit

Permalink
move PyDict::get_item_with_error to PyDict::get_item
Browse files Browse the repository at this point in the history
  • Loading branch information
davidhewitt committed Jul 19, 2023
1 parent 7958f03 commit 897b830
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 27 deletions.
1 change: 1 addition & 0 deletions newsfragments/3330.changed.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Change `PyDict::get_item` to no longer suppress arbitrary exceptions (the return type is now `PyResult<Option<&PyAny>>` instead of `Option<&PyAny>`), and deprecate `PyDict::get_item_with_error`.
42 changes: 15 additions & 27 deletions src/types/dict.rs
Original file line number Diff line number Diff line change
Expand Up @@ -134,35 +134,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<K>(&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<K>(&self, key: K) -> PyResult<Option<&PyAny>>
pub fn get_item<K>(&self, key: K) -> PyResult<Option<&PyAny>>
where
K: ToPyObject,
{
Expand All @@ -184,6 +159,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<K>(&self, key: K) -> PyResult<Option<&PyAny>>
where
K: ToPyObject,
{
self.get_item(key)
}

/// Sets an item value.
///
/// This is equivalent to the Python statement `self[key] = value`.
Expand Down

0 comments on commit 897b830

Please sign in to comment.