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

Return reference to self? #572

Closed
RKennedy9064 opened this issue Aug 11, 2019 · 3 comments
Closed

Return reference to self? #572

RKennedy9064 opened this issue Aug 11, 2019 · 3 comments

Comments

@RKennedy9064
Copy link

Is it currently possible to return a reference to self as a PyResult? Currently I can return a struct with a PyResult, but get an error when trying to return a reference.

#[pyclass]
#[derive(Clone, Copy)]
struct Test {}

#[pymethods]
impl Test {
    fn test_self(self) -> PyResult<Test> {
        Ok(self)
    }

    fn test_self_reference(&self) -> PyResult<&Test> {
        Ok(self)
    }

    fn test_self_mut_reference(&mut self) -> PyResult<&mut Test> {
        Ok(self)
    }
}

error[E0277]: the trait bound `std::result::Result<&Test, pyo3::err::PyErr>: pyo3::derive_utils::IntoPyResult<_>` is not satisfied
  --> src\lib.rs:21:1
   |
21 | #[pymethods]
   | ^^^^^^^^^^^^ the trait `pyo3::derive_utils::IntoPyResult<_>` is not implemented for `std::result::Result<&Test, pyo3::err::PyErr>`

error[E0277]: the trait bound `std::result::Result<&mut Test, pyo3::err::PyErr>: pyo3::derive_utils::IntoPyResult<_>` is not satisfied
  --> src\lib.rs:21:1
   |
21 | #[pymethods]
   | ^^^^^^^^^^^^ the trait `pyo3::derive_utils::IntoPyResult<_>` is not implemented for `std::result::Result<&mut Test, pyo3::err::PyErr>`

I was able to find the source code for it here https://github.com/PyO3/pyo3/blob/master/src/derive_utils.rs, but didn't see any documentation related to it. Is it currently possible to return a reference to self? Returning a struct works when it derives Clone and Copy, but is it possible to return a reference for structs that contain fields that don't derive from Clone/Copy? Any information would be greatly appreciated.

@kngwyu
Copy link
Member

kngwyu commented Aug 11, 2019

I recommend

#[pyclass]
#[derive(Clone, Copy)]
struct Test {}

#[pymethods]
impl Test {
    fn test_self_reference(slf: PyRef<Self>, py: Python) -> PyResult<PyObject> {
        Ok(slf.to_object(py))
    }
}

@kngwyu kngwyu closed this as completed Aug 11, 2019
@kngwyu
Copy link
Member

kngwyu commented Aug 11, 2019

See also #573
It enables a bit more convinient approach

@RKennedy9064
Copy link
Author

@kngwyu Thanks for the quick response. Your example works perfectly, so I'll use that for now and switch it over once the PR you made is accepted. Thanks for the help!

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

No branches or pull requests

2 participants