Skip to content

Instantly share code, notes, and snippets.

@daniil-konovalenko
Created January 5, 2021 14:50
Show Gist options
  • Save daniil-konovalenko/41ce420a9bd1d714050bebbafcbfb7aa to your computer and use it in GitHub Desktop.
Save daniil-konovalenko/41ce420a9bd1d714050bebbafcbfb7aa to your computer and use it in GitHub Desktop.
use pyo3::prelude::*;
use pyo3::type_object::PyBorrowFlagLayout;
use pyo3::{PyClass, PyTypeInfo};
use serde::{de, ser, Deserialize, Deserializer, Serialize, Serializer};
pub fn serialize<S, T>(value: &Py<T>, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
T: Serialize + PyClass,
{
Python::with_gil(|py| {
value
.try_borrow(py)
.map_err(|e| ser::Error::custom(e.to_string()))?
.serialize(serializer)
})
}
pub fn deserialize<'de, D, T>(deserializer: D) -> Result<Py<T>, D::Error>
where
D: Deserializer<'de>,
T: Deserialize<'de> + PyClass + Into<PyClassInitializer<T>>,
<T as PyTypeInfo>::BaseLayout: PyBorrowFlagLayout<<T as PyTypeInfo>::BaseType>,
{
let res = T::deserialize(deserializer)?;
Python::with_gil(|py| Py::new(py, res).map_err(|e| de::Error::custom(e.to_string())))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment