5 个版本 (3 个破坏性版本)
| 0.4.0 | 2024年6月25日 |
|---|---|
| 0.3.0 | 2024年4月15日 |
| 0.2.1 | 2024年2月8日 |
| 0.2.0 | 2023年12月1日 |
| 0.1.0 | 2023年11月20日 |
#269 in 编码
每月下载量1,994
43KB
654 行
serde-pyobject
PyO3的PyAny作为serde数据格式
用法
将 T: Serialize 序列化为 &'py PyAny
use serde::Serialize;
use pyo3::{Python, Bound, types::{PyAny, PyAnyMethods, PyDict}};
use serde_pyobject::{to_pyobject, pydict};
#[derive(Serialize)]
struct A {
a: u32,
b: String,
}
Python::with_gil(|py| {
let a = A { a: 1, b: "test".to_string() };
let obj: Bound<PyAny> = to_pyobject(py, &a).unwrap();
assert!(obj.eq(pydict! { py, "a" => 1, "b" => "test" }.unwrap()).unwrap());
});
将 &'py PyAny 反序列化为 T: Deserialize<'de>
use serde::Deserialize;
use pyo3::{Python, Bound, types::{PyAny, PyAnyMethods, PyDict}};
use serde_pyobject::{from_pyobject, pydict};
#[derive(Debug, PartialEq, Deserialize)]
struct A {
a: u32,
b: String,
}
Python::with_gil(|py| {
let a: Bound<PyDict> = pydict! { py,
"a" => 1,
"b" => "test"
}
.unwrap();
let a: A = from_pyobject(a).unwrap();
assert_eq!(a, A { a: 1, b: "test".to_string() });
});
Python和serde数据模型之间的映射
| serde数据模型 | PyO3类型 | Rust | Python |
|---|---|---|---|
i8,i16,i32,i64,isizeu8,u16,u32,u64,usize |
PyLong |
123 |
123 |
f32,f64 |
PyFloat |
1.0 |
1.0 |
bool |
PyBool |
true |
true |
char,string |
PyString |
'a',"test" |
"a","test" |
| option | PyAny [^1] |
None,Some(1) |
None,1 |
| unit | PyTuple |
() |
() |
| unit struct | PyTuple |
struct Unit |
() |
| unit variant | PyDict |
E::A 在 enum E { A, B } |
"A" |
| newtype 结构体 | PyDict |
A(32) 为 struct A(u8) |
32 |
| newtype 变体 | PyDict |
E::N(41) 为 enum E { N(u8) } |
{ "N": 41 } |
| 序列 | PyList |
vec![1, 2, 3] |
[1, 2, 3] |
| 元组 | PyTuple |
(1, "测试") |
(1, "测试") |
| 元组结构体 | PyDict |
T(1, "a") 为 struct T(u32, String) |
(1, "a") |
| 元组变体 | PyDict |
E::S(1, 2) 为 enum E { S(u8, u8) } |
{ "S": (1, 2) } |
| 映射 | PyDict |
hashmap!{ "a".to_string() => 1, "b".to_string() => 2 } |
{ "a": 1, "b": 2 } |
| struct | PyDict |
A { a: 1, b: "test" } 为 struct A { a: u32, b: String } |
{ "a": 1, "b": "测试"} |
| 结构体变体 | PyDict |
E::S { r: 1, g: 2, b: 3 } 的 enum E { S { r: u8, g: u8, b: u8 } } |
{ "S": { "r": 1, "g": 2, "b": 3 } } |
[^1]: Some(value) 序列化为 value
许可证
© 2023 Jij Inc.
本项目许可协议为以下之一:
- Apache License, Version 2.0, (LICENSE-APACHE 或 https://apache.ac.cn/licenses/LICENSE-2.0)
- MIT 许可证 (LICENSE-MIT 或 https://open-source.org.cn/licenses/MIT)
由您选择。
依赖项
约2.5MB
约54K SLoC