Debian Codegraph @

README.md

raw symbols SCIP
1 # Pythonize
2
3 This is an experimental serializer for Rust's serde ecosystem, which can convert Rust objects to Python values and back.
4
5 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
6 that which is produced directly by `pythonize`.
7
8 ## Usage
9
10 This crate converts Rust types which implement the [Serde] serialization
11 traits into Python objects using the [PyO3] library.
12
13 Pythonize has two main public APIs: `pythonize` and `depythonize`.
14
15 </div>
16
17 [Serde]: https://github.com/serde-rs/serde
18 [PyO3]: https://github.com/PyO3/pyo3
19
20 ## Examples
21
22 ```rust
23 use serde::{Serialize, Deserialize};
24 use pyo3::prelude::*;
25 use pythonize::{depythonize, pythonize};
26
27 #[derive(Debug, Serialize, Deserialize, PartialEq)]
28 struct Sample {
29 foo: String,
30 bar: Option<usize>
31 }
32
33 let sample = Sample {
34 foo: "Foo".to_string(),
35 bar: None
36 };
37
38 Python::attach(|py| {
39 // Rust -> Python
40 let obj = pythonize(py, &sample).unwrap();
41
42 assert_eq!("{'foo': 'Foo', 'bar': None}", &format!("{}", obj.repr().unwrap()));
43
44 // Python -> Rust
45 let new_sample: Sample = depythonize(&obj).unwrap();
46
47 assert_eq!(new_sample, sample);
48 })
49 ```
50
51 ## Features
52
53 ### `arbitrary_precision`
54
55 Enable support for `serde_json`'s `arbitrary_precision` feature, which allows handling numbers that exceed the range of `i128`/`u128` when converting `serde_json::Value` to and from Python.
56
57 ```toml
58 [dependencies]
59 pythonize = { version = "0.28", features = ["arbitrary_precision"] }
60 ```