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

如何通过PyO3将Rust枚举类型返回至Python模块?

用PyO3将Rust枚举暴露给Python的解决方案

要让Rust枚举能被Python识别并正常输出,需要通过PyO3的宏将枚举注册为Python类,并添加必要的方法让输出更友好。以下是具体实现步骤:

1. 配置依赖

确保Cargo.toml中包含PyO3的正确依赖,启用extension-module特性:

[package]
name = "pymylib"
version = "0.1.0"
edition = "2021"

[dependencies]
pyo3 = { version = "0.21", features = ["extension-module"] }

2. 修改Rust枚举定义

给Lang枚举添加#[pyclass]属性,让PyO3将其转换为Python可识别的类型:

use pyo3::prelude::*;

#[pyclass]
pub enum Lang {
    Deu,
    Eng,
    Fra,
}

3. 添加Python友好的字符串表示

为枚举实现__str__和__repr__方法,让Python打印时能输出清晰的标识:

#[pymethods]
impl Lang {
    fn __str__(&self) -> &str {
        match self {
            Lang::Deu => "Lang::Deu",
            Lang::Eng => "Lang::Eng",
            Lang::Fra => "Lang::Fra",
        }
    }

    fn __repr__(&self) -> &str {
        self.__str__()
    }
}

4. 修正函数返回类型并注册模块

修改detect_language的返回类型为PyResult<Lang>,并在模块中注册枚举类:

#[pyfunction]
fn detect_language(text: &str) -> PyResult<Lang> {
    // 替换为你的语言检测逻辑
    let res = if text.contains("Ceci") {
        Lang::Fra
    } else if text.contains("Hello") {
        Lang::Eng
    } else {
        Lang::Deu
    };
    Ok(res)
}

#[pymodule]
fn pymylib(_py: Python, m: &PyModule) -> PyResult<()> {
    // 注册Lang类到模块
    m.add_class::<Lang>()?;
    m.add_function(wrap_pyfunction!(detect_language, m)?)?;
    Ok(())
}

5. Python端测试

构建并安装包后,Python代码可以直接使用枚举类型并正常打印:

from pymylib import detect_language, Lang

res = detect_language('Ceci est un test')
print(res)  # 输出: Lang::Fra
print(isinstance(res, Lang))  # 输出: True

构建与安装

使用maturin工具构建并安装:

pip install maturin
maturin develop

内容的提问来源于stack exchange,提问作者LeMoussel

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.20 18:22:55