https://github.com/davidhewitt/pythonize
https://github.com/davidhewitt/pythonize
Last synced: 8 months ago
JSON representation
- Host: GitHub
- URL: https://github.com/davidhewitt/pythonize
- Owner: davidhewitt
- License: mit
- Created: 2020-08-07T15:53:37.000Z (over 5 years ago)
- Default Branch: main
- Last Pushed: 2025-04-25T11:00:41.000Z (9 months ago)
- Last Synced: 2025-04-25T12:19:26.728Z (9 months ago)
- Language: Rust
- Size: 141 KB
- Stars: 232
- Watchers: 5
- Forks: 33
- Open Issues: 9
-
Metadata Files:
- Readme: README.md
- Changelog: CHANGELOG.md
- Funding: .github/FUNDING.yml
- License: LICENSE
Awesome Lists containing this project
- awesome-rust-python - pythonize - Python serialization library for Rust types. (Utilities)
README
# 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`.
[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
}
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);
})
```