-
Notifications
You must be signed in to change notification settings - Fork 763
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Add new trait IntoPyObject #2316
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -184,6 +184,98 @@ pub trait IntoPy<T>: Sized { | |
fn into_py(self, py: Python<'_>) -> T; | ||
} | ||
|
||
/// Defines a conversion from a Rust type to a Python object. | ||
/// | ||
/// It functions similarly to std's [`Into`](std::convert::Into) trait, | ||
/// but requires a [GIL token](Python) as an argument. | ||
/// Many functions and traits internal to PyO3 require this trait as a bound, | ||
/// so a lack of this trait can manifest itself in different error messages. | ||
/// | ||
/// # Examples | ||
/// ## With `#[pyclass]` | ||
/// The easiest way to implement `IntoPy` is by exposing a struct as a native Python object | ||
/// by annotating it with [`#[pyclass]`](crate::prelude::pyclass). | ||
/// | ||
/// ```rust | ||
/// use pyo3::prelude::*; | ||
/// | ||
/// #[pyclass] | ||
/// struct Number { | ||
/// #[pyo3(get, set)] | ||
/// value: i32, | ||
/// } | ||
/// ``` | ||
/// Python code will see this as an instance of the `Number` class with a `value` attribute. | ||
/// | ||
/// ## Conversion to a Python object | ||
/// | ||
/// However, it may not be desirable to expose the existence of `Number` to Python code. | ||
/// `IntoPy` allows us to define a conversion to an appropriate Python object. | ||
/// ```rust | ||
/// use pyo3::prelude::*; | ||
/// | ||
/// struct Number { | ||
/// value: i32, | ||
/// } | ||
/// | ||
/// impl IntoPy<PyObject> for Number { | ||
/// fn into_py(self, py: Python<'_>) -> PyObject { | ||
/// // delegates to i32's IntoPy implementation. | ||
/// self.value.into_py(py) | ||
/// } | ||
/// } | ||
/// ``` | ||
/// Python code will see this as an `int` object. | ||
/// | ||
/// ## Dynamic conversion into Python objects. | ||
/// It is also possible to return a different Python object depending on some condition. | ||
/// This is useful for types like enums that can carry different types. | ||
/// | ||
/// ```rust | ||
/// use pyo3::prelude::*; | ||
/// | ||
/// enum Value { | ||
/// Integer(i32), | ||
/// String(String), | ||
/// None, | ||
/// } | ||
/// | ||
/// impl IntoPy<PyObject> for Value { | ||
/// fn into_py(self, py: Python<'_>) -> PyObject { | ||
/// match self { | ||
/// Self::Integer(val) => val.into_py(py), | ||
/// Self::String(val) => val.into_py(py), | ||
/// Self::None => py.None(), | ||
/// } | ||
/// } | ||
/// } | ||
/// # fn main() { | ||
/// # Python::with_gil(|py| { | ||
/// # let v = Value::Integer(73).into_py(py); | ||
/// # let v = v.extract::<i32>(py).unwrap(); | ||
/// # | ||
/// # let v = Value::String("foo".into()).into_py(py); | ||
/// # let v = v.extract::<String>(py).unwrap(); | ||
/// # | ||
/// # let v = Value::None.into_py(py); | ||
/// # let v = v.extract::<Option<Vec<i32>>>(py).unwrap(); | ||
/// # }); | ||
/// # } | ||
/// ``` | ||
/// Python code will see this as any of the `int`, `string` or `None` objects. | ||
#[cfg_attr(docsrs, doc(alias = "IntoPyCallbackOutput"))] | ||
pub trait IntoPyObject: Sized { | ||
type Target; | ||
|
||
/// Performs the conversion. | ||
fn into_py(self, py: Python<'_>) -> Py<Self::Target>; | ||
|
||
/// Performs the conversion. | ||
fn into_object(self, py: Python<'_>) -> PyObject { | ||
unsafe { Py::from_owned_ptr(py, self.into_py(py).into_ptr()) } | ||
} | ||
} | ||
|
||
/// `FromPyObject` is implemented by various types that can be extracted from | ||
/// a Python object reference. | ||
/// | ||
|
@@ -244,6 +336,17 @@ where | |
} | ||
} | ||
|
||
impl<T> IntoPyObject for Option<T> | ||
where | ||
T: IntoPyObject, | ||
{ | ||
type Target = PyAny; | ||
|
||
fn into_py(self, py: Python<'_>) -> PyObject { | ||
self.map_or_else(|| py.None(), |val| val.into_object(py)) | ||
} | ||
} | ||
|
||
/// `()` is converted to Python `None`. | ||
impl ToPyObject for () { | ||
fn to_object(&self, py: Python<'_>) -> PyObject { | ||
|
@@ -431,6 +534,13 @@ impl IntoPy<Py<PyTuple>> for () { | |
} | ||
} | ||
|
||
impl IntoPyObject for () { | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Note that IMO this is a bit annoying, and However without specialization, we need to do some fudging in the macros to fix the There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. To me, it would seem preferable to fix the special case of the type of the return value of functions that do not return anything instead of ingraining this into the conversion traits. There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. @adamreichold I think that we're saying the same thing? At the moment the conversion traits encode this special case, however really this should just be part of the There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Yes, certainly. I just wanted to echo
which sounded like you did not fully convince yourself yet. |
||
type Target = PyTuple; | ||
fn into_py(self, py: Python<'_>) -> Py<PyTuple> { | ||
PyTuple::empty(py).into() | ||
} | ||
} | ||
|
||
/// Raw level conversion between `*mut ffi::PyObject` and PyO3 types. | ||
/// | ||
/// # Safety | ||
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I think this communicates the difference between these methods better.