PyO3 Asyncio
Rust bindings for Python's Asyncio Library. This crate facilitates interactions between Rust Futures and Python Coroutines and manages the lifecycle of their corresponding event loops.
-
Contributing Notes: github
PyO3 Asyncio is a brand new part of the broader PyO3 ecosystem. Feel free to open any issues for feature requests or bugfixes for this crate.
Known Problems
This library can give spurious failures during finalization prior to PyO3 release v0.13.2
. Make sure your PyO3 dependency is up-to-date!
Quickstart
Rust Applications
Here we initialize the runtime, import Python's asyncio
library and run the given future to completion using Python's default EventLoop
and async-std
. Inside the future, we convert asyncio
sleep into a Rust future and await it.
More details on the usage of this library can be found in the API docs.
use *;
async
The same application can be written to use tokio
instead using the #[pyo3_asyncio::tokio::main]
attribute.
use *;
async
PyO3 Native Rust Modules
PyO3 Asyncio can also be used to write native modules with async functions.
Add the [lib]
section to Cargo.toml
to make your library a cdylib
that Python can import.
[]
= "my_async_module"
= ["cdylib"]
Make your project depend on pyo3
with the extension-module
feature enabled and select your
pyo3-asyncio
runtime:
For async-std
:
[]
= { = "0.13", = ["extension-module"] }
= { = "0.13", = ["async-std-runtime"] }
= "1.9"
For tokio
:
[]
= { = "0.13", = ["extension-module"] }
= { = "0.13", = ["tokio-runtime"] }
= "1.4"
Export an async function that makes use of async-std
:
//! lib.rs
use ;
If you want to use tokio
instead, here's what your module should look like:
//! lib.rs
use ;
Build your module and rename libmy_async_module.so
to my_async_module.so
&&
Now, point your PYTHONPATH
to the directory containing my_async_module.so
, then you'll be able
to import and use it:
>>> import
>>> from
>>>
>>> # should sleep for 1s
>>> asyncio.get_event_loop() ))
>>>
)
Note that we are using
EventLoop.run_until_complete
here instead of the newerasyncio.run
. That is becauseasyncio.run
will set up its own internal event loop thatpyo3_asyncio
will not be aware of. For this reason, runningpyo3_asyncio
conversions throughasyncio.run
is not currently supported.This restriction may be lifted in a future release.
MSRV
Currently the MSRV for this library is 1.46.0, but if you don't need to use the async-std-runtime
feature, you can use rust 1.45.0.
async-std
depends onsocket2
which fails to compile under 1.45.0.