File: README.md

package info (click to toggle)
rust-pythonize 0.25.0-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 192 kB
  • sloc: makefile: 2
file content (49 lines) | stat: -rw-r--r-- 1,312 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
# 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 main public APIs: `pythonize` and `depythonize`.

</div>

[Serde]: https://github.com/serde-rs/serde
[PyO3]: https://github.com/PyO3/pyo3

# Examples

```rust
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);
})
```