pyo3
pyo3 copied to clipboard
Issues with async support / Tokio
I attempt to compile the following code with experimental-async feature enabled:
#[pyclass]
struct Sender {
_inner: IPCSender
}
#[pymethods]
impl Sender {
#[new]
async fn new(printname: String) -> PyResult<Self> {
let ipcsender = IPCSender::new(&printname).await?;
Ok(Self { _inner: ipcsender })
}
}
#[pymodule]
fn python_ipc(m: &Bound<'_, PyModule>) -> PyResult<()> {
m.add_function(wrap_pyfunction!(sum_as_string, m)?)?;
m.add_class::<Sender>()?;
Ok(())
}
However, I get this error message:
error[E0599]: no method named `convert` found for opaque type `impl Future<Output = Result<Sender, PyErr>>` in the current scope
--> src/lib.rs:11:1
|
11 | #[pymethods]
| ^^^^^^^^^^^^ method not found in `impl Future<Output = Result<Sender, PyErr>>`
|
= note: this error originates in the attribute macro `pymethods` (in Nightly builds, run with -Z macro-backtrace for more info)
I tried adding:
static RT: OnceLock<tokio::runtime::Runtime> = OnceLock::new();
RT.get_or_init(|| tokio::runtime::Runtime::new().expect("Unable to start Tokio runtime"));
to python_ipc function, but it still doesn't work.
IPCSender is a struct from a local crate, which uses tokio runtime.
I suspect that we (currently) don't support async constructors.
Same issue here, I'm using a workaround from pyo3-async-runtimes:
#[new]
#[pyo3(signature = (serial_number = None))]
fn new(serial_number: Option<&str>) -> BoardResult<Self> {
pyo3_async_runtimes::tokio::get_runtime().block_on(async {
let client = connect_to_board(USB_DEVICE_NAME, serial_number).await?;
Ok(Self { client })
})
}