pub trait FromPyObjectOwned<'py>: for<'a> FromPyObject<'a, 'py> { }Expand description
A data structure that can be extracted without borrowing any data from the input.
This is primarily useful for trait bounds. For example a FromPyObject implementation of a
wrapper type may be able to borrow data from the input, but a FromPyObject implementation of
a collection type may only extract owned data.
For example PyList will not hand out references tied to its own lifetime, but “owned”
references independent of it. (Similar to Vec<Arc<T>> where you clone the Arc<T> out).
This makes it impossible to collect borrowed types in a collection, since they would not borrow
from the original PyList, but the much shorter lived element reference. See the example
below.
pub struct MyWrapper<T>(T);
impl<'a, 'py, T> FromPyObject<'a, 'py> for MyWrapper<T>
where
T: FromPyObject<'a, 'py>
{
type Error = T::Error;
fn extract(obj: Borrowed<'a, 'py, PyAny>) -> Result<Self, Self::Error> {
obj.extract().map(MyWrapper)
}
}
pub struct MyVec<T>(Vec<T>);
impl<'py, T> FromPyObject<'_, 'py> for MyVec<T>
where
T: FromPyObjectOwned<'py> // 👈 can only extract owned values, because each `item` below
// is a temporary short lived owned reference
{
type Error = PyErr;
fn extract(obj: Borrowed<'_, 'py, PyAny>) -> Result<Self, Self::Error> {
let mut v = MyVec(Vec::new());
for item in obj.try_iter()? {
v.0.push(item?.extract::<T>().map_err(Into::into)?);
}
Ok(v)
}
}Dyn Compatibility§
This trait is not dyn compatible.
In older versions of Rust, dyn compatibility was called "object safety", so this trait is not object safe.