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

ENH: boiler plate for IntoPy<PyObject> #4458

Closed
attack68 opened this issue Aug 20, 2024 · 2 comments · Fixed by #4495
Closed

ENH: boiler plate for IntoPy<PyObject> #4458

attack68 opened this issue Aug 20, 2024 · 2 comments · Fixed by #4495

Comments

@attack68
Copy link
Contributor

I may very well be implementing a weak design pattern, but I regularly use an enum to control Rust structs passed as Python classes. The enum itself does not need to be python class (so refutes the doc comment "The easiest way to implement IntoPy is by exposing a struct as a native Python object by annotating it with [#[pyclass]]")

The FromPyObject can be automatically derived, but I often implement IntoPy<PyObject> directly using repeatable boiler plate code such as the following. Can this be automatic in pyo3?

#[derive(Debug, Clone, PartialEq, FromPyObject)]
pub(crate) enum Shape {
    Square(Square),
    Circle(Circle),
    Triangle(Triangle),
}

impl IntoPy<PyObject> for CurveInterpolator {
    fn into_py(self, py: Python<'_>) -> PyObject {
        macro_rules! into_py {
            ($obj: ident) => {
                Py::new(py, $obj).unwrap().to_object(py)
            }
        }

        match self {
            Shape::Square(s) => into_py!(s),
            Shape::Circle(s) => into_py!(s),
            Shape::Triangle(s) => into_py!(s),
        }
    }
}
@davidhewitt
Copy link
Member

In PyO3 0.23 we are going to release a new trait IntoPyObject to replace IntoPy based on what we've learned over time. I would be open to discussing the possibility of adding an IntoPyObject derive too (not necessarily in 0.23, though that might be very appealing from the view of helping users migrate). cc @Icxolu

@Icxolu
Copy link
Contributor

Icxolu commented Aug 20, 2024

That sounds interesting and could be quite useful for migrating. For these newtype enums the conversion seems indeed quite straight forward, but for more complex enums and structs it's a bit unclear what the resulting Python object should be... maybe PyDict and/or PyTuple depending on whether the fields are named or not.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

3 participants