ITADN
davidhewitt/pythonize
davidhewitt/pythonize · 文件 下载 ZIP
文件最后提交记录最后更新时间
README.md
以下内容由 AI 翻译,如有问题请点此提交 issue 反馈

Pythonize

这是一个为 Rust 的 serde 生态系统设计的序列化工具,能够将 Rust 对象转换为 Python 值,反之亦然。

目前,它生成的 Python 数据结构应与 serde_json 生成的结构_极为_相似;也就是说,对由 serde_json 编码后的值调用 Python 的 json.loads(),所得到的结构应与直接由 pythonize 生成的结构完全一致。

使用方式

该库利用 PyO3 库,将实现了 Serde 序列化特性的 Rust 类型转换为 Python 对象。

Pythonize 提供两个主要的公共 API:pythonizedepythonize

示例

use serde::{Serialize, Deserialize};
use pyo3::prelude::*;
use pythonize::{depythonize, pythonize};

#[derive(Debug, Serialize, Deserialize, PartialEq)]
struct Sample {
    foo: String,
    bar: Option<usize>
}

let sample = Sample {
    foo: "Foo".to_string(),
    bar: None
};

Python::attach(|py| {
    // Rust -> Python
    let obj =  pythonize(py, &sample).unwrap();

    assert_eq!("{'foo': 'Foo', 'bar': None}", &format!("{}", obj.repr().unwrap()));

    // Python -> Rust
    let new_sample: Sample = depythonize(&obj).unwrap();

    assert_eq!(new_sample, sample);
})

功能特性

arbitrary_precision

启用对 serde_jsonarbitrary_precision 功能的支持,该功能可在将 serde_json::Value 转换为 Python 及从 Python 转换回来时,处理超出 i128/u128 范围的数字。

[dependencies]
pythonize = { version = "0.29", features = ["arbitrary_precision"] }