pyo3 icon indicating copy to clipboard operation
pyo3 copied to clipboard

Add new trait IntoPyObject

Open davidhewitt opened this issue 3 years ago • 1 comments
trafficstars

This is throwing out a concept that I've been pondering for a while to progress with the design of the to-python conversion traits.

It replaces IntoPy<T> generic trait with a trait IntoPyObject which has an associated type defined as follows:

pub trait IntoPyObject: Sized {
    type Target;

    /// Converts to the known target Python type.
    fn into_py(self, py: Python<'_>) -> Py<Self::Target>;

    /// Converts to a generic Python type. Equivalent to `self.into_py().into()`.
    fn into_object(self, py: Python<'_>) -> PyObject;
}

The names are intended to line up with the ToPyObject trait which has the to_object method. We could also have TryIntoPyObject trait, potentially, with a similar design.

The advantages I see of doing this:

  • Users can call into_py() and get Py<T> rather than Py<PyAny>, helping avoid to need an immediate cast to work with the Python object.
  • Avoids inference errors caused when multiple implementations of IntoPy<T> exist for a given type.
  • Opens the way for us to have #[derive(IntoPyObject)].

davidhewitt avatar Apr 19 '22 07:04 davidhewitt

I like it a lot. I agree that the () -> None transform only should be made for function returns.

birkenfeld avatar Apr 19 '22 07:04 birkenfeld

Closing as this is very outdated and #4041 is an attempt to kickstart future discussion in this space.

davidhewitt avatar Apr 03 '24 08:04 davidhewitt