14 个版本 (7 个重大更新)

0.20.0 2023年11月11日
0.19.0 2023年7月23日
0.18.0 2023年2月2日
0.17.0 2022年10月7日
0.13.2 2021年2月20日

#318FFI

Download history 10673/week @ 2024-03-30 9208/week @ 2024-04-06 8893/week @ 2024-04-13 8701/week @ 2024-04-20 54528/week @ 2024-04-27 52983/week @ 2024-05-04 14828/week @ 2024-05-11 9075/week @ 2024-05-18 6530/week @ 2024-05-25 7282/week @ 2024-06-01 10270/week @ 2024-06-08 8521/week @ 2024-06-15 7983/week @ 2024-06-22 6732/week @ 2024-06-29 6512/week @ 2024-07-06 6781/week @ 2024-07-13

每月下载量 29,296
19 个crate中使用(通过 pyo3-asyncio

Apache-2.0

51KB
448

PyO3 Asyncio

Actions Status codecov crates.io minimum rustc 1.63

RustPythonAsyncio 库 提供绑定。此crate促进了 Rust Futures 和 Python 协程之间的交互,并管理它们对应的事件循环的生命周期。

PyO3 Asyncio 是 PyO3 生态系统中的新成员。请随时为此crate提交任何功能请求或错误修复问题。

如果您是新手,最好的入门方式是阅读下面的入门指南!对于 v0.13v0.14 的用户,我强烈推荐阅读 迁移部分,以了解 v0.14v0.15 中发生了什么变化。

使用方法

与 PyO3 类似,PyO3 Asyncio 支持以下软件版本

  • Python 3.7 及以上(CPython 和 PyPy)
  • Rust 1.48 及以上

PyO3 Asyncio 入门

如果您正在使用一个利用异步函数的Python库,或者想要为异步Rust库提供Python绑定,那么pyo3-asyncio可能正是您需要的工具。它提供了Python和Rust中异步函数之间的转换,并针对流行的Rust运行时(如tokioasync-std)提供了一等支持。此外,所有异步Python代码都运行在默认的asyncio事件循环上,因此pyo3-asyncio应与现有的Python库很好地配合工作。

在下文中,我们将概述pyo3-asyncio,解释如何使用PyO3调用异步Python函数,如何从Python调用异步Rust函数,以及如何配置您的代码库来管理这两个运行时。

快速入门

以下是立即开始的一些示例!关于这些示例中概念更详细的说明可以在下文中找到。

Rust应用程序

在这里,我们初始化运行时,导入Python的asyncio库,并使用Python的默认EventLoopasync-std运行给定的future,直到完成。在future内部,我们将asyncio休眠转换为Rust future并等待它。

# Cargo.toml dependencies
[dependencies]
pyo3 = { version = "0.20" }
pyo3-asyncio = { version = "0.20", features = ["attributes", "async-std-runtime"] }
async-std = "1.9"
//! main.rs

use pyo3::prelude::*;

#[pyo3_asyncio::async_std::main]
async fn main() -> PyResult<()> {
    let fut = Python::with_gil(|py| {
        let asyncio = py.import("asyncio")?;
        // convert asyncio.sleep into a Rust Future
        pyo3_asyncio::async_std::into_future(asyncio.call_method1("sleep", (1.into_py(py),))?)
    })?;

    fut.await?;

    Ok(())
}

该应用程序可以写为使用tokio,只需使用#[pyo3_asyncio::tokio::main]属性。

# Cargo.toml dependencies
[dependencies]
pyo3 = { version = "0.20" }
pyo3-asyncio = { version = "0.20", features = ["attributes", "tokio-runtime"] }
tokio = "1.9"
//! main.rs

use pyo3::prelude::*;

#[pyo3_asyncio::tokio::main]
async fn main() -> PyResult<()> {
    let fut = Python::with_gil(|py| {
        let asyncio = py.import("asyncio")?;
        // convert asyncio.sleep into a Rust Future
        pyo3_asyncio::tokio::into_future(asyncio.call_method1("sleep", (1.into_py(py),))?)
    })?;

    fut.await?;

    Ok(())
}

有关此库的更多详细信息,请参阅API文档和以下入门指南。

PyO3原生Rust模块

PyO3 Asyncio还可以用于编写具有异步函数的原生模块。

[lib]部分添加到Cargo.toml,使您的库成为Python可以导入的cdylib

[lib]
name = "my_async_module"
crate-type = ["cdylib"]

使用具有启用extension-module功能的pyo3依赖项并选择您的pyo3-asyncio运行时

对于async-std

[dependencies]
pyo3 = { version = "0.20", features = ["extension-module"] }
pyo3-asyncio = { version = "0.20", features = ["async-std-runtime"] }
async-std = "1.9"

对于tokio

[dependencies]
pyo3 = { version = "0.20", features = ["extension-module"] }
pyo3-asyncio = { version = "0.20", features = ["tokio-runtime"] }
tokio = "1.9"

导出一个使用async-std的异步函数

//! lib.rs

use pyo3::{prelude::*, wrap_pyfunction};

#[pyfunction]
fn rust_sleep(py: Python) -> PyResult<&PyAny> {
    pyo3_asyncio::async_std::future_into_py(py, async {
        async_std::task::sleep(std::time::Duration::from_secs(1)).await;
        Ok(())
    })
}

#[pymodule]
fn my_async_module(py: Python, m: &PyModule) -> PyResult<()> {
    m.add_function(wrap_pyfunction!(rust_sleep, m)?)?;

    Ok(())
}

如果您想使用tokio,则您的模块应如下所示

//! lib.rs

use pyo3::{prelude::*, wrap_pyfunction};

#[pyfunction]
fn rust_sleep(py: Python) -> PyResult<&PyAny> {
    pyo3_asyncio::tokio::future_into_py(py, async {
        tokio::time::sleep(std::time::Duration::from_secs(1)).await;
        Ok(())
    })
}

#[pymodule]
fn my_async_module(py: Python, m: &PyModule) -> PyResult<()> {
    m.add_function(wrap_pyfunction!(rust_sleep, m)?)?;
    Ok(())
}

您可以使用maturin构建模块(请参阅PyO3指南中的使用Rust在Python中部分以获取设置说明)。之后,您应该能够运行Python REPL来尝试它。

maturin develop && python3
🔗 Found pyo3 bindings
🐍 Found CPython 3.8 at python3
    Finished dev [unoptimized + debuginfo] target(s) in 0.04s
Python 3.8.5 (default, Jan 27 2021, 15:41:15)
[GCC 9.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import asyncio
>>>
>>> from my_async_module import rust_sleep
>>>
>>> async def main():
>>>     await rust_sleep()
>>>
>>> # should sleep for 1s
>>> asyncio.run(main())
>>>

在Rust中等待异步Python函数

让我们看看一个简单的异步Python函数

# Sleep for 1 second
async def py_sleep():
    await asyncio.sleep(1)

Python中的异步函数仅仅是返回一个coroutine对象的函数。对于我们来说,我们实际上不需要知道太多关于这些coroutine对象。关键因素是调用异步函数的方式与调用常规函数一样,唯一的区别是我们必须对返回的对象进行特殊处理。

在Python中,有一些特殊的关键词,比如await,但在Rust中等待这个协程,我们首先需要将其转换为Rust版本的协程:一个Future。这就是pyo3-asyncio发挥作用的地方。pyo3_asyncio::into_future为我们执行这个转换。

use pyo3::prelude::*;

#[pyo3_asyncio::tokio::main]
async fn main() -> PyResult<()> {
    let future = Python::with_gil(|py| -> PyResult<_> {
        // import the module containing the py_sleep function
        let example = py.import("example")?;

        // calling the py_sleep method like a normal function
        // returns a coroutine
        let coroutine = example.call_method0("py_sleep")?;

        // convert the coroutine into a Rust future using the
        // tokio runtime
        pyo3_asyncio::tokio::into_future(coroutine)
    })?;

    // await the future
    future.await?;

    Ok(())
}

如果您想了解更多关于协程awaitables的信息,请查看Python 3 asyncio文档

在Python中等待Rust Future

这里有一个与之前相同的异步函数,它使用async-std运行时在Rust中编写。

/// Sleep for 1 second
async fn rust_sleep() {
    async_std::task::sleep(std::time::Duration::from_secs(1)).await;
}

与Python类似,Rust的异步函数也返回一个特殊对象,称为Future

let future = rust_sleep();

我们可以将这个Future对象转换为Python,使其成为awaitable。这告诉Python可以使用await关键字。为了做到这一点,我们将调用pyo3_asyncio::async_std::future_into_py

use pyo3::prelude::*;

async fn rust_sleep() {
    async_std::task::sleep(std::time::Duration::from_secs(1)).await;
}

#[pyfunction]
fn call_rust_sleep(py: Python) -> PyResult<&PyAny> {
    pyo3_asyncio::async_std::future_into_py(py, async move {
        rust_sleep().await;
        Ok(())
    })
}

在Python中,我们可以像调用任何其他异步函数一样调用这个pyo3函数。

from example import call_rust_sleep

async def rust_sleep():
    await call_rust_sleep()

管理事件循环

Python的事件循环需要一些特殊处理,尤其是在主线程方面。Python的一些asyncio特性,如适当的信号处理,需要控制主线程,这通常与Rust不太兼容。

幸运的是,Rust的事件循环非常灵活,并且不需要控制主线程,所以在pyo3-asyncio中,我们决定处理Rust/Python互操作的最佳方法是将主线程交给Python,并在后台运行Rust的事件循环。遗憾的是,由于大多数事件循环实现更喜欢控制主线程,这仍然会使一些事情变得尴尬。

PyO3 Asyncio 初始化

由于Python需要控制主线程,我们无法使用Rust运行时提供的方便的proc宏来处理main函数或#[test]函数。相反,PyO3的初始化必须从main函数中进行,并且主线程必须在pyo3_asyncio::run_foreverpyo3_asyncio::async_std::run_until_complete上阻塞。

由于我们必须在这些函数上阻塞,所以我们不能使用#[async_std::main]#[tokio::main],因为在一个异步函数中进行长时间的阻塞调用不是一个好主意。

内部,这些#[main] proc宏被扩展为类似于以下的内容

fn main() {
    // your async main fn
    async fn _main_impl() { /* ... */ }
    Runtime::new().block_on(_main_impl());
}

在由 block_on 驱动的 Future 中进行长时间阻塞调用,会阻止该线程执行任何其他操作,并可能导致某些运行时出现麻烦(这实际上会导致单线程运行时发生死锁!)。许多运行时都有某种 spawn_blocking 机制,可以避免这个问题,但在这里我们无法使用它,因为我们需要在 线程上进行阻塞。

因此,pyo3-asyncio 提供了自己的一套 proc macros,以提供这种初始化。这些宏旨在反映 async-stdtokio 的初始化,同时满足 Python 运行时的需求。

以下是使用 async-std 运行时进行 PyO3 初始化的完整示例

use pyo3::prelude::*;

#[pyo3_asyncio::async_std::main]
async fn main() -> PyResult<()> {
    // PyO3 is initialized - Ready to go

    let fut = Python::with_gil(|py| -> PyResult<_> {
        let asyncio = py.import("asyncio")?;

        // convert asyncio.sleep into a Rust Future
        pyo3_asyncio::async_std::into_future(
            asyncio.call_method1("sleep", (1.into_py(py),))?
        )
    })?;

    fut.await?;

    Ok(())
}

关于 asyncio.run 的说明

从 Python 3.7+ 开始,使用 asyncio 运行顶层协程的推荐方法是使用 asyncio.run。在 v0.13 中,我们不建议使用此函数,因为存在初始化问题,但在 v0.14 中,使用此函数是完全可以接受的……但有前提。

由于我们的 Rust <--> Python 转换需要 Python 事件循环的引用,这造成了一个问题。想象一下,我们有一个 PyO3 Asyncio 模块,它定义了一个类似于先前示例中的 rust_sleep 函数。你可能合理地认为可以直接像这样将其传递给 asyncio.run

import asyncio

from my_async_module import rust_sleep

asyncio.run(rust_sleep())

你可能惊讶地发现这会引发一个错误

Traceback (most recent call last):
  File "example.py", line 5, in <module>
    asyncio.run(rust_sleep())
RuntimeError: no running event loop

这里发生的事情是,我们在未来实际上在由 asyncio.run 创建的事件循环上运行之前,调用了 rust_sleep。这虽然不符合直觉,但却是预期的行为,不幸的是,在 PyO3 Asyncio 内部似乎没有很好的方法来解决这个问题。

然而,我们可以通过一个简单的解决方案使此示例工作

import asyncio

from my_async_module import rust_sleep

# Calling main will just construct the coroutine that later calls rust_sleep.
# - This ensures that rust_sleep will be called when the event loop is running,
#   not before.
async def main():
    await rust_sleep()

# Run the main() coroutine at the top-level instead
asyncio.run(main())

非标准 Python 事件循环

Python 允许你使用除默认的 asyncio 事件循环之外的替代方案。一个流行的替代方案是 uvloop。在 v0.13 中,使用非标准事件循环有点麻烦,但在 v0.14 中,这变得非常简单。

在 PyO3 Asyncio 本地扩展中使用 uvloop

# Cargo.toml

[lib]
name = "my_async_module"
crate-type = ["cdylib"]

[dependencies]
pyo3 = { version = "0.20", features = ["extension-module"] }
pyo3-asyncio = { version = "0.20", features = ["tokio-runtime"] }
async-std = "1.9"
tokio = "1.9"
//! lib.rs

use pyo3::{prelude::*, wrap_pyfunction};

#[pyfunction]
fn rust_sleep(py: Python) -> PyResult<&PyAny> {
    pyo3_asyncio::tokio::future_into_py(py, async {
        tokio::time::sleep(std::time::Duration::from_secs(1)).await;
        Ok(())
    })
}

#[pymodule]
fn my_async_module(_py: Python, m: &PyModule) -> PyResult<()> {
    m.add_function(wrap_pyfunction!(rust_sleep, m)?)?;

    Ok(())
}
$ maturin develop && python3
🔗 Found pyo3 bindings
🐍 Found CPython 3.8 at python3
    Finished dev [unoptimized + debuginfo] target(s) in 0.04s
Python 3.8.8 (default, Apr 13 2021, 19:58:26)
[GCC 7.3.0] :: Anaconda, Inc. on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import asyncio
>>> import uvloop
>>>
>>> import my_async_module
>>>
>>> uvloop.install()
>>>
>>> async def main():
...     await my_async_module.rust_sleep()
...
>>> asyncio.run(main())
>>>

在 Rust 应用程序中使用 uvloop

在 Rust 应用程序中使用 uvloop 有点复杂,但经过一些修改后仍然可行。

不幸的是,我们无法在非标准事件循环中使用 #[pyo3_asyncio::<runtime>::main] 属性。这是因为 #[pyo3_asyncio::<runtime>::main] proc macro 必须在我们可以安装 uvloop 策略之前与 Python 事件循环交互。

[dependencies]
async-std = "1.9"
pyo3 = "0.20"
pyo3-asyncio = { version = "0.20", features = ["async-std-runtime"] }
//! main.rs

use pyo3::{prelude::*, types::PyType};

fn main() -> PyResult<()> {
    pyo3::prepare_freethreaded_python();

    Python::with_gil(|py| {
        let uvloop = py.import("uvloop")?;
        uvloop.call_method0("install")?;

        // store a reference for the assertion
        let uvloop = PyObject::from(uvloop);

        pyo3_asyncio::async_std::run(py, async move {
            // verify that we are on a uvloop.Loop
            Python::with_gil(|py| -> PyResult<()> {
                assert!(uvloop
                    .as_ref(py)
                    .getattr("Loop")?
                    .downcast::<PyType>()
                    .unwrap()
                    .is_instance(pyo3_asyncio::async_std::get_current_loop(py)?)?);
                Ok(())
            })?;

            async_std::task::sleep(std::time::Duration::from_secs(1)).await;

            Ok(())
        })
    })
}

更多信息

迁移指南

从0.13迁移到0.14

那么,从v0.13v0.14有什么变化吗?

实际上,有很多变化。在v0.13的初始化行为中存在一些相当严重的缺陷。虽然最好在不更改公共API的情况下解决这些问题,但我认为最好是破坏一些旧API,而不是完全改变现有函数的底层行为。我意识到这将带来一些麻烦,所以希望这个部分能帮助您顺利过渡。

为了使事情变得容易一些,我决定保留大部分旧API与新API(附带一些弃用警告,以鼓励用户远离它)并行使用。应该可以在旧版v0.13 API和新版v0.14 API之间切换,这将允许您分阶段而不是一次性升级您的应用程序。

在您开始之前,我建议您查看事件循环引用和ContextVars,以更好地了解这些变化背后的动机以及使用新转换的细微差别。

0.14 突出显示

  • Tokio初始化现在是懒加载的。
    • 如果您使用的是多线程调度程序,则不需要配置。
    • 调用pyo3_asyncio::tokio::init_multithreadpyo3_asyncio::tokio::init_multithread_once可以简单地删除。
    • 调用pyo3_asyncio::tokio::init_current_threadpyo3_asyncio::tokio::init_current_thread_once需要特别注意。
    • 通过将一个tokio::runtime::Builder传递给pyo3_asyncio::tokio::init而不是一个tokio::runtime::Runtime来进行自定义运行时配置。
  • 已添加一组新的、更正确的函数来替换v0.13转换。
    • pyo3_asyncio::into_future_with_loop
    • pyo3_asyncio::<runtime>::future_into_py_with_loop
    • pyo3_asyncio::<runtime>::local_future_into_py_with_loop
    • pyo3_asyncio::<runtime>::into_future
    • pyo3_asyncio::<runtime>::future_into_py
    • pyo3_asyncio::<runtime>::local_future_into_py
    • pyo3_asyncio::<runtime>::get_current_loop
  • pyo3_asyncio::try_init不再需要,如果您只使用0.14转换。
  • ThreadPoolExecutor不再在启动时自动配置。
    • 幸运的是,这似乎对v0.13代码影响不大,这意味着现在您可以按需手动配置执行器。

将您的代码升级到0.14

  1. 修复PyO3 0.14初始化问题。

    • PyO3 0.14将自动初始化行为限制在“auto-initialize”之下。您可以在项目中启用“auto-initialize”行为,或将对pyo3::prepare_freethreaded_python()的调用添加到程序开始处。
    • 如果您正在使用#[pyo3_asyncio::<runtime>::main]过程宏属性,则可以跳过此步骤。#[pyo3_asyncio::<runtime>::main]将在启动时调用pyo3::prepare_freethreaded_python(),而不管项目的“auto-initialize”功能如何。
  2. 修复tokio初始化。

    • 调用pyo3_asyncio::tokio::init_multithreadpyo3_asyncio::tokio::init_multithread_once可以简单地删除。

    • 如果您正在使用当前线程调度器,您需要在初始化期间手动启动运行的线程。

      let mut builder = tokio::runtime::Builder::new_current_thread();
      builder.enable_all();
      
      pyo3_asyncio::tokio::init(builder);
      std::thread::spawn(move || {
          pyo3_asyncio::tokio::get_runtime().block_on(
              futures::future::pending::<()>()
          );
      });
      
    • 可以将自定义的tokio::runtime::Builder配置传递给pyo3_asyncio::tokio::init。在首次调用pyo3_asyncio::tokio::get_runtime()时,将延迟实例化tokio::runtime::Runtime

  3. 如果您正在您的应用程序中使用pyo3_asyncio::run_forever,则应切换到更手动的方法。

    run_forever不是在Python中运行事件循环的推荐方法,所以可能最好远离它。这个函数可能需要为0.14进行更改,但由于它被认为是一个边缘情况,因此决定用户在需要时可以手动调用它。

    use pyo3::prelude::*;
    
    fn main() -> PyResult<()> {
        pyo3::prepare_freethreaded_python();
    
        Python::with_gil(|py| {
            let asyncio = py.import("asyncio")?;
    
            let event_loop = asyncio.call_method0("new_event_loop")?;
            asyncio.call_method1("set_event_loop", (event_loop,))?;
    
            let event_loop_hdl = PyObject::from(event_loop);
    
            pyo3_asyncio::tokio::get_runtime().spawn(async move {
                tokio::time::sleep(std::time::Duration::from_secs(1)).await;
    
                // Stop the event loop manually
                Python::with_gil(|py| {
                    event_loop_hdl
                        .as_ref(py)
                        .call_method1(
                            "call_soon_threadsafe",
                            (event_loop_hdl
                                .as_ref(py)
                                .getattr("stop")
                                .unwrap(),),
                        )
                        .unwrap();
                })
            });
    
            event_loop.call_method0("run_forever")?;
            Ok(())
        })
    }
    
  4. 用它们的新版本替换转换。

    您可能会遇到有关使用get_running_loopget_event_loop的一些问题。有关这些新转换及其使用方法的更多详细信息,请参阅事件循环引用和ContextVars

    • pyo3_asyncio::into_future替换为pyo3_asyncio::<runtime>::into_future
    • pyo3_asyncio::<runtime>::into_coroutine 替换为 pyo3_asyncio::<runtime>::future_into_py
    • pyo3_asyncio::get_event_loop 替换为 pyo3_asyncio::<runtime>::get_current_loop
  5. 将所有转换替换为其 v0.14 对应版本后,可以安全地删除 pyo3_asyncio::try_init

版本 v0.15 中已删除 v0.13 API。

从 0.14 迁移到 0.15+

对 API 进行了一些修改,以支持从 Python 和 contextvars 模块进行适当的取消操作。

  • 任何 cancellable_future_into_pylocal_cancellable_future_into_py 转换都可以替换为其 future_into_pylocal_future_into_py 对应版本。

    取消支持在 0.15 中成为默认行为。

  • *_with_loop 转换的实例应替换为较新的 *_with_locals 转换。

    use pyo3::prelude::*;
    
    Python::with_gil(|py| -> PyResult<()> {
    
        // *_with_loop conversions in 0.14
        //
        // let event_loop = pyo3_asyncio::get_running_loop(py)?;
        //
        // let fut = pyo3_asyncio::tokio::future_into_py_with_loop(
        //     event_loop,
        //     async move { Ok(Python::with_gil(|py| py.None())) }
        // )?;
        //
        // should be replaced with *_with_locals in 0.15+
        let fut = pyo3_asyncio::tokio::future_into_py_with_locals(
            py,
            pyo3_asyncio::tokio::get_current_locals(py)?,
            async move { Ok(()) }
        )?;
    
        Ok(())
    });
    
  • scopescope_local 变体现在接受 TaskLocals 而不是 event_loop。您通常只需将 event_loop 替换为 pyo3_asyncio::TaskLocals::new(event_loop).copy_context(py)?

  • future_into_pyfuture_into_py_with_localslocal_future_into_pylocal_future_into_py_with_locals 的返回类型现在受限于约束的 IntoPy<PyObject> 而不是要求返回类型为 PyObject。这可以使未来的返回类型更加灵活,但具体类型不明确时(例如,使用 into() 时),推理可能会失败。有时可以简单地删除 into()

  • runrun_until_complete 现在可以返回任何 Send + 'static 值。

从 0.15 迁移到 0.16

实际上,API 中变化不大。我很高兴地说,PyO3 Asyncio 在 0.16 中已经达到了相当稳定的状态。就大部分而言,0.16 是关于清理和从 API 中删除弃用函数。

PyO3 0.16 带来了一些自己的 API 变更,但其中对 PyO3 Asyncio 影响最大的变更之一是决定停止支持 Python 3.6。PyO3 Asyncio 一直使用一些工作区/黑客技巧来支持 Python asyncio 库的 3.7 之前的版本,这些现在不再必要。因此,PyO3 Asyncio 的底层实现现在要干净一些。

PyO3 Asyncio 0.15 包含了一些重要的 API 修复,以添加对适当任务取消的支持,并允许在 Python 协程中保留/使用 contextvars。这导致了某些 0.14 函数的弃用,这些函数用于处理边缘情况,并采用了一些更正确的版本,这些弃用的函数现在已从 0.16 的 API 中移除。

此外,随着 PyO3 Asyncio 0.16 的发布,该库现在对将 Python 的异步生成器转换为 Rust 的 Stream 提供了实验性支持。目前有两个版本 v1v2,性能和类型签名略有不同,所以我希望得到一些反馈,看看哪一个对下游用户来说最好。只需启用 unstable-streams 功能即可!

逆转换,即 Rust 的 Stream 转换为 Python 的异步生成器,可能会在后续版本中提供,如果需要的话!

依赖关系

~1.5MB
~36K SLoC