#python #pyo3 #deserialize #convert #object #values #type

pythonize

Serde Serializer & Deserializer from Rust <--> Python, backed by PyO3

13 releases (breaking)

0.21.1 Apr 2, 2024
0.20.0 Oct 15, 2023
0.19.0 Jun 11, 2023
0.18.0 Jan 22, 2023
0.12.0 Nov 22, 2020

#32 in FFI

Download history 8609/week @ 2023-12-21 8051/week @ 2023-12-28 10785/week @ 2024-01-04 10286/week @ 2024-01-11 11482/week @ 2024-01-18 10967/week @ 2024-01-25 11453/week @ 2024-02-01 10619/week @ 2024-02-08 11088/week @ 2024-02-15 12281/week @ 2024-02-22 11467/week @ 2024-02-29 11421/week @ 2024-03-07 11776/week @ 2024-03-14 13677/week @ 2024-03-21 13630/week @ 2024-03-28 10727/week @ 2024-04-04

52,296 downloads per month
Used in 24 crates (20 directly)

MIT license

49KB
1.5K SLoC

Pythonize

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.

Usage

This crate converts Rust types which implement the Serde serialization traits into Python objects using the PyO3 library.

Pythonize has two public APIs: pythonize and depythonize.

Examples

use serde::{Serialize, Deserialize};
use pyo3::Python;
use pythonize::{depythonize, 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(obj.as_ref(py)).unwrap();

assert_eq!(new_sample, sample);

Dependencies

~3–9.5MB
~73K SLoC