You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Rust-pyo3转换自定义类型至Bound<PyAny>时遇生命周期错误求助

Rust自定义类型转Bound<PyAny>的生命周期问题及扩展场景

我正尝试将自定义Rust类型转换为Bound<PyAny>,但即便添加了显式生命周期标识符,仍持续遇到Rust生命周期错误。我的函数代码如下:

pub fn do_something<'a>(
    specs: &Bound<PyAny>,
    numbs: Vec<f64>,
) -> PyResult<Bound<'a, PyAny>> {
    ...
      // do something with specs and numbs
      // get spec
    ...

    Python::with_gil(|py : Python<'a>|{
        let s = match spec {
            Operator::variant1(x) => {
                let pyref: Py<Variant1Wrapper> =
                    Py::new(py, Variant1Wrapper { internal: x }).unwrap();
                pyref.to_object(py).into_bound(py)
            }
            Operator::variant2(x) => {
                let pyref: Py<Variant2Wrapper> =
                    Py::new(py, Variant2Wrapper { internal: x }).unwrap();
                pyref.to_object(py).into_bound(py)
            }
        };

        Ok(s)

    })
}

rust-analyser在pyref.to_object(py).into_bound(py)处给出以下错误:

lifetime may not live long enough
returning this value requires that '1 must outlive '2
do_something.rs(170, 33): has type `pyo3::Python<'1>`
do_something.rs(170, 40): return type of closure is pyo3::Bound<'2, pyo3::PyAny>

UPDATE:@kmdreko的解答已解决初始问题。

此外,若函数参数中无Bound<T>类型(如下列代码),应如何处理?

pub fn do_something<'a>(
    numbs: Vec<f64>,
) -> PyResult<Bound<'a, PyAny>> 

内容的提问来源于stack exchange,提问作者May be a greyhound

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.22 10:53:13