#[pymethods]
Expand description
pyo3::pymethods
with async support.
For each async methods, generate a additional function prefixed by async_
, decorated with
#[pyo3(name = ...)]
. Original async methods are kept in a separate impl, while the original
impl is decorated with pyo3::pymethods
.
Python async backend can be specified using macro argument (default to asyncio
).
If allow_threads
is passed in arguments, GIL will be released for future polling (see
AllowThreads
)
ยงExample
#[pyo3::pyclass]
struct Counter(usize);
#[pyo3_async::pymethods(trio)]
impl Counter {
fn incr_sync(&mut self) -> usize {
self.0 += 1;
self.0
}
// Arguments needs to implement `Send + 'static`, so `self` must be passed using `Py<Self>`
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)
})
}
}
generates
#[pyo3::pyclass]
struct Counter(usize);
#[::pyo3::pymethods]
impl Counter {
fn incr_sync(&mut self) -> usize {
self.0 += 1;
self.0
}
#[pyo3(name = "incr_async")]
fn async_incr_async(self_: pyo3::Py<Self>) -> ::pyo3_async::trio::Coroutine {
::pyo3_async::trio::Coroutine::from_future(Counter::incr_async(self_))
}
}
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)
})
}
}