Skip to content

How to run async code from current class in pymethods #3

@szandara

Description

@szandara

From your example we can run async code like this. However, it's not clear to me how I can invoke async functions from the same class. Image I have to call another async method from this, how would I do that?

impl Counter {
     async fn incr_async(self_: pyo3::Py<Self>) -> pyo3::PyResult<usize> {
        pyo3::Python::with_gil(|gil| {
            let mut this = self_.borrow_mut(gil);
            this.0 += 1;
             Ok(this.0)
       })
   }
}

Example.

impl Counter {
     async fn incr_async(self_: pyo3::Py<Self>) -> pyo3::PyResult<usize> {
        pyo3::Python::with_gil(|gil| {
            let mut this = self_.borrow_mut(gil);
            // This does not compile because the context is sync.
            Ok(this.another_sync_method().await)
       })
   }
}

Also, I cannot return a future here because the gil lifetime will expire. I can use the async_std::task::block_on inside the GIL block but it would be nice to have something cleaner that keeps living on the same async loop.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions