Skip to content

Commit

Permalink
add DowncastIntoError::into_inner (#3829)
Browse files Browse the repository at this point in the history
  • Loading branch information
davidhewitt committed Feb 12, 2024
1 parent 5b9b76f commit 94b7d7e
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 0 deletions.
8 changes: 8 additions & 0 deletions src/err/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,14 @@ impl<'py> DowncastIntoError<'py> {
to: to.into(),
}
}

/// Consumes this `DowncastIntoError` and returns the original object, allowing continued
/// use of it after a failed conversion.
///
/// See [`downcast_into`][PyAnyMethods::downcast_into] for an example.
pub fn into_inner(self) -> Bound<'py, PyAny> {
self.from
}
}

impl PyErr {
Expand Down
21 changes: 21 additions & 0 deletions src/types/any.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1561,6 +1561,27 @@ pub trait PyAnyMethods<'py> {
T: PyTypeCheck;

/// Like `downcast` but takes ownership of `self`.
///
/// In case of an error, it is possible to retrieve `self` again via [`DowncastIntoError::into_inner`].
///
/// # Example
///
/// ```rust
/// use pyo3::prelude::*;
/// use pyo3::types::{PyDict, PyList};
///
/// Python::with_gil(|py| {
/// let obj: Bound<'_, PyAny> = PyDict::new_bound(py).into_any();
///
/// let obj: Bound<'_, PyAny> = match obj.downcast_into::<PyList>() {
/// Ok(_) => panic!("obj should not be a list"),
/// Err(err) => err.into_inner(),
/// };
///
/// // obj is a dictionary
/// assert!(obj.downcast_into::<PyDict>().is_ok());
/// })
/// ```
fn downcast_into<T>(self) -> Result<Bound<'py, T>, DowncastIntoError<'py>>
where
T: PyTypeCheck;
Expand Down

0 comments on commit 94b7d7e

Please sign in to comment.