Skip to content
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

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions pyo3-macros-backend/src/pyclass.rs
Original file line number Diff line number Diff line change
Expand Up @@ -737,6 +737,13 @@ impl<'a> PyClassImplsBuilder<'a> {
_pyo3::IntoPy::into_py(_pyo3::Py::new(py, self).unwrap(), py)
}
}

impl _pyo3::IntoPyObject for #cls {
type Target = #cls;
fn into_py(self, py: _pyo3::Python) -> _pyo3::Py<#cls> {
_pyo3::Py::new(py, self).unwrap()
}
}
}
} else {
quote! {}
Expand Down
10 changes: 5 additions & 5 deletions src/callback.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,8 @@ use crate::err::{PyErr, PyResult};
use crate::exceptions::PyOverflowError;
use crate::ffi::{self, Py_hash_t};
use crate::panic::PanicException;
use crate::{GILPool, IntoPyPointer};
use crate::{IntoPy, PyObject, Python};
use crate::{GILPool, IntoPyObject, IntoPyPointer};
use crate::{PyObject, Python};
use std::any::Any;
use std::os::raw::c_int;
use std::panic::UnwindSafe;
Expand Down Expand Up @@ -53,7 +53,7 @@ where

impl<T> IntoPyCallbackOutput<*mut ffi::PyObject> for T
where
T: IntoPy<PyObject>,
T: IntoPyObject,
{
#[inline]
fn convert(self, py: Python<'_>) -> PyResult<*mut ffi::PyObject> {
Expand Down Expand Up @@ -118,11 +118,11 @@ impl IntoPyCallbackOutput<usize> for usize {

impl<T> IntoPyCallbackOutput<PyObject> for T
where
T: IntoPy<PyObject>,
T: IntoPyObject,
{
#[inline]
fn convert(self, py: Python<'_>) -> PyResult<PyObject> {
Ok(self.into_py(py))
Ok(self.into_object(py))
}
}

Expand Down
110 changes: 110 additions & 0 deletions src/conversion.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
fn into_object(self, py: Python<'_>) -> PyObject {
fn into_object(self, py: Python<'_>) -> Py<PyAny> {

I think this communicates the difference between these methods better.

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.
///
Expand Down Expand Up @@ -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 {
Expand Down Expand Up @@ -431,6 +534,13 @@ impl IntoPy<Py<PyTuple>> for () {
}
}

impl IntoPyObject for () {
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Note that IntoPy<PyObject> for () becomes None, and IntoPy<Py<PyTuple>> becomes ().

IMO this is a bit annoying, and ().into_py() should be an empty tuple

However without specialization, we need to do some fudging in the macros to fix the () case as a #[pyfunction] return value. I'm pretty sure I know how to do this.

Copy link
Member

Choose a reason for hiding this comment

The 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.

Copy link
Member Author

Choose a reason for hiding this comment

The 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 #[pyfunction] / #[pymethods] macro. (With min_specialization it could probably be part of the IntoPyCallbackOutput trait in the future, however I won't hold my breath.)

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, certainly. I just wanted to echo

IMO this is a bit annoying, and ().into_py() should be an empty tuple

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
Expand Down
17 changes: 15 additions & 2 deletions src/conversions/array.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,12 @@ use crate::{exceptions, PyErr};
#[cfg(min_const_generics)]
mod min_const_generics {
use super::invalid_sequence_length;
use crate::{FromPyObject, IntoPy, PyAny, PyObject, PyResult, PyTryFrom, Python, ToPyObject};
use crate::{
types::PyList, FromPyObject, IntoPyObject, Py, PyAny, PyObject, PyResult, PyTryFrom,
Python, ToPyObject,
};

impl<T, const N: usize> IntoPy<PyObject> for [T; N]
impl<T, const N: usize> crate::IntoPy<PyObject> for [T; N]
where
T: ToPyObject,
{
Expand All @@ -14,6 +17,16 @@ mod min_const_generics {
}
}

impl<T, const N: usize> IntoPyObject for [T; N]
where
T: ToPyObject,
{
type Target = PyList;
fn into_py(self, py: Python<'_>) -> Py<PyList> {
PyList::new(py, self.as_ref()).into()
}
}

impl<'a, T, const N: usize> FromPyObject<'a> for [T; N]
where
T: FromPyObject<'a>,
Expand Down
16 changes: 16 additions & 0 deletions src/conversions/hashbrown.rs
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,22 @@ where
}
}

impl<K, V, H> IntoPyObject for hashbrown::HashMap<K, V, H>
where
K: hash::Hash + cmp::Eq + IntoPyObject,
V: IntoPyObject,
H: hash::BuildHasher,
{
type Target = PyDict;

fn into_py(self, py: Python<'_>) -> Py<PyDict> {
let iter = self
.into_iter()
.map(|(k, v)| (k.into_py(py), v.into_py(py)));
IntoPyDict::into_py_dict(iter, py)
}
}

impl<'source, K, V, S> FromPyObject<'source> for hashbrown::HashMap<K, V, S>
where
K: FromPyObject<'source> + cmp::Eq + hash::Hash,
Expand Down
15 changes: 15 additions & 0 deletions src/conversions/indexmap.rs
Original file line number Diff line number Diff line change
Expand Up @@ -121,6 +121,21 @@ where
}
}

impl<K, V, H> IntoPyObject for indexmap::IndexMap<K, V, H>
where
K: hash::Hash + cmp::Eq + IntoPyObject,
V: IntoPyObject,
H: hash::BuildHasher,
{
type Target = PyDict;
fn into_py(self, py: Python<'_>) -> PyObject {
let iter = self
.into_iter()
.map(|(k, v)| (k.into_py(py), v.into_py(py)));
IntoPyDict::into_py_dict(iter, py).into()
}
}

impl<'source, K, V, S> FromPyObject<'source> for indexmap::IndexMap<K, V, S>
where
K: FromPyObject<'source> + cmp::Eq + hash::Hash,
Expand Down
Loading