14 个版本 (破坏性更新)
0.22.0 | 2024 年 8 月 10 日 |
---|---|
0.21.1 | 2024 年 4 月 2 日 |
0.20.0 | 2023 年 10 月 15 日 |
0.19.0 | 2023 年 6 月 11 日 |
0.12.0 | 2020 年 11 月 22 日 |
32 在 FFI 中
59,891 每月下载量
在 28 个 crate 中使用 (24 个直接使用)
62KB
1.5K SLoC
Pythonize
这是一个 Rust 的 serde 生态系统的实验性序列化器,可以将 Rust 对象转换为 Python 值,反之亦然。
目前,它生成的 Python 结构应该与由 serde_json
生成的结构非常相似;即对由 serde_json
编码的值调用 Python 的 json.loads()
应该产生与 pythonize
直接生成的相同结构。
用法
此 crate 使用 Serde 序列化特性将 Rust 类型转换为 Python 对象,使用 PyO3 库。
Pythonize 有两个公共 API:`pythonize` 和 `depythonize_bound`。
⚠️ 警告:API 更新中 🛠️
PyO3 0.21 引入了一个重大新的 API,称为“Bound” API,这是基于新的智能指针 Bound<T>
,pythonize 也正在这样做。
示例
use serde::{Serialize, Deserialize};
use pyo3::Python;
use pythonize::{depythonize_bound, pythonize};
#[derive(Debug, Serialize, Deserialize, PartialEq)]
struct Sample {
foo: String,
bar: Option<usize>
}
let gil = Python::acquire_gil();
let py = gil.python();
let sample = Sample {
foo: "Foo".to_string(),
bar: None
};
// Rust -> Python
let obj = pythonize(py, &sample).unwrap();
assert_eq!("{'foo': 'Foo', 'bar': None}", &format!("{}", obj.as_ref(py).repr().unwrap()));
// Python -> Rust
let new_sample: Sample = depythonize_bound(obj.into_bound(py)).unwrap();
assert_eq!(new_sample, sample);
依赖关系
~2.5MB
~54K SLoC