pyo3/conversions/std/
option.rs1use crate::{
2 conversion::IntoPyObject, types::any::PyAnyMethods, Bound, BoundObject, FromPyObject, PyAny,
3 PyResult, Python,
4};
5
6impl<'py, T> IntoPyObject<'py> for Option<T>
7where
8 T: IntoPyObject<'py>,
9{
10 type Target = PyAny;
11 type Output = Bound<'py, Self::Target>;
12 type Error = T::Error;
13
14 fn into_pyobject(self, py: Python<'py>) -> Result<Self::Output, Self::Error> {
15 self.map_or_else(
16 || Ok(py.None().into_bound(py)),
17 |val| {
18 val.into_pyobject(py)
19 .map(BoundObject::into_any)
20 .map(BoundObject::into_bound)
21 },
22 )
23 }
24}
25
26impl<'a, 'py, T> IntoPyObject<'py> for &'a Option<T>
27where
28 &'a T: IntoPyObject<'py>,
29{
30 type Target = PyAny;
31 type Output = Bound<'py, Self::Target>;
32 type Error = <&'a T as IntoPyObject<'py>>::Error;
33
34 #[inline]
35 fn into_pyobject(self, py: Python<'py>) -> Result<Self::Output, Self::Error> {
36 self.as_ref().into_pyobject(py)
37 }
38}
39
40impl<'py, T> FromPyObject<'py> for Option<T>
41where
42 T: FromPyObject<'py>,
43{
44 fn extract_bound(obj: &Bound<'py, PyAny>) -> PyResult<Self> {
45 if obj.is_none() {
46 Ok(None)
47 } else {
48 obj.extract().map(Some)
49 }
50 }
51}