检查 pyO3 Rust 中输入的类型

问题描述 投票:0回答:1

有人可以给出 pyO3 中函数的完整/工作示例吗?该函数接受单个输入,并根据输入是否具有类型

true/false
返回
scipy.sparse.csr_matrix

我知道 pyO3 有

is_instance
,但这似乎需要有一个代表类型的对象。我知道
get_type
,但是假设你已经拥有正确类型的对象,这让我很困惑。

python rust pyo3
1个回答
0
投票

您将获得一个类型,就像在 Python 中获得它一样:

import scipy.sparse

is_instance = isinstance(value, scipy.sparse.csr_matrix)

所以:

let py: Python<'_>; // Given

let scipy_parse = py.import_bound("scipy.sparse")?;
let csr_matrix = scipy_parse.getattr("csr_matrix")?;

let is_instance = value.is_instance(&csr_matrix)?;

当然,最好缓存类型:

static CSR_MATRIX: GILOnceCell<Py<PyAny>> = GILOnceCell::new();

fn csr_matrix(py: Python<'_>) -> PyResult<&'static Bound<'_, PyAny>> {
    let result = CSR_MATRIX.get_or_try_init(py, || {
        let scipy_parse = py.import_bound("scipy.sparse")?;
        Ok(scipy_parse.getattr("csr_matrix")?.unbind())
    })?;
    Ok(result.bind(py))
}

let is_instance = value.is_instance(csr_matrix(py)?)?;
© www.soinside.com 2019 - 2024. All rights reserved.