Crates.io | pythonize |
lib.rs | pythonize |
version | 0.23.0 |
source | src |
created_at | 2020-08-12 07:35:57.037369 |
updated_at | 2024-11-22 16:54:29.485175 |
description | Serde Serializer & Deserializer from Rust <--> Python, backed by PyO3. |
homepage | https://github.com/davidhewitt/pythonize |
repository | https://github.com/davidhewitt/pythonize |
max_upload_size | |
id | 275710 |
size | 81,694 |
This is an experimental serializer for Rust's serde ecosystem, which can convert Rust objects to Python values and back.
At the moment the Python structures it produces should be very similar to those which are produced by serde_json
; i.e. calling Python's json.loads()
on a value encoded by serde_json
should produce an identical structure to
that which is produced directly by pythonize
.
This crate converts Rust types which implement the Serde serialization traits into Python objects using the PyO3 library.
Pythonize has two main public APIs: pythonize
and depythonize
.
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::with_gil(|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);
})