add `DowncastIntoError::into_inner` (#3829)
This commit is contained in:
parent
5b9b76fe58
commit
94b7d7e434
|
@ -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 {
|
||||||
|
|
|
@ -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;
|
||||||
|
|
Loading…
Reference in New Issue