Pyo3: Python callback from Rust

Created on 9 Jul 2019  路  1Comment  路  Source: PyO3/pyo3

Hi,

i'm trying to call a Python function from my Rust Code #120 says to use ObjectProtocol::is_callable and ObjectProtocol::call but doesn't explain how to do it, i've looked at the documentation but can't find anything related to what i'm trying to do.

my code looks as follows:

use pyo3::exceptions;
use pyo3::prelude::*;
#[pymodule]
fn py_test(py: Python, m: &PyModule) -> PyResult<()> {
    #[pyfn(m, "sum_as_string")]
    fn sum_as_string(py: Python, a: usize, b: usize, callback: PyObject) -> PyResult<String> {
        println!("Hello from Rust!");
        println!("callback is: {:?}", callback);
        println!(
            "callback is: {:?}",
            ObjectProtocol::is_callable(&callback)
        );
        println!("Raising exception...");
        Ok("bye!".to_string())
    }
    Ok(())
}

and i'm getting the following error when trying to compile:

error[E0277]: the trait bound `pyo3::object::PyObject: pyo3::instance::PyNativeType` is not satisfied
  --> src\lib.rs:16:13
   |
16 |             ObjectProtocol::is_callable(&callback)
   |             ^^^^^^^^^^^^^^^^^^^^^^^^^^^ the trait `pyo3::instance::PyNativeType` is not implemented for `pyo3::object::PyObject`
   |
   = note: required because of the requirements on the impl of `pyo3::objectprotocol::ObjectProtocol` for `pyo3::object::PyObject`
   = note: required by `pyo3::objectprotocol::ObjectProtocol::is_callable`

error: aborting due to previous error

For more information about this error, try `rustc --explain E0277`.
error: Could not compile `py_test`.

To learn more, run the command again with --verbose.

i'm using Python 3.7.3 on Microsoft Windows [Version 10.0.17134.829] and rustc 1.37.0-nightly (5d8f59f4b 2019-06-04) in case that's relevant.

thanks in advance for any help

Most helpful comment

I got it to work by trial and error:

use pyo3::prelude::*;
#[pymodule]
fn py_test(py: Python, m: &PyModule) -> PyResult<()> {
    #[pyfn(m, "sum_as_string")]
    fn sum_as_string(py: Python, a: usize, b: usize, callback: PyObject) -> PyResult<PyObject> {
        println!("Hello from Rust!");
        callback.call(py, (a, b, (a + b).to_string()), None)
    }
    Ok(())
}

>All comments

I got it to work by trial and error:

use pyo3::prelude::*;
#[pymodule]
fn py_test(py: Python, m: &PyModule) -> PyResult<()> {
    #[pyfn(m, "sum_as_string")]
    fn sum_as_string(py: Python, a: usize, b: usize, callback: PyObject) -> PyResult<PyObject> {
        println!("Hello from Rust!");
        callback.call(py, (a, b, (a + b).to_string()), None)
    }
    Ok(())
}
Was this page helpful?
0 / 5 - 0 ratings

Related issues

konstin picture konstin  路  5Comments

nbigaouette picture nbigaouette  路  4Comments

acminor picture acminor  路  3Comments

fcangialosi picture fcangialosi  路  6Comments

konstin picture konstin  路  5Comments