add `DowncastIntoError::into_inner` (#3829)

This commit is contained in:
David Hewitt 2024-02-12 21:40:05 +00:00 committed by GitHub
parent 5b9b76fe58
commit 94b7d7e434
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 29 additions and 0 deletions

View File

@ -97,6 +97,14 @@ impl<'py> DowncastIntoError<'py> {
to: to.into(), 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 { impl PyErr {

View File

@ -1561,6 +1561,27 @@ pub trait PyAnyMethods<'py> {
T: PyTypeCheck; T: PyTypeCheck;
/// Like `downcast` but takes ownership of `self`. /// 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>> fn downcast_into<T>(self) -> Result<Bound<'py, T>, DowncastIntoError<'py>>
where where
T: PyTypeCheck; T: PyTypeCheck;