feat: py bindings refactoring (#317)

* feat: py bindings refactoring

* unset version in pyproject.toml
This commit is contained in:
stefan-gorules
2025-02-16 20:19:02 +01:00
committed by GitHub
parent 2da4b69441
commit ff34aff821
11 changed files with 240 additions and 144 deletions
+26 -3
View File
@@ -1,6 +1,8 @@
use pyo3::prelude::{PyDictMethods, PyListMethods};
use pyo3::types::{PyDict, PyList};
use pyo3::{Bound, IntoPyObject, IntoPyObjectExt, PyAny, PyErr, PyResult, Python};
use anyhow::Context;
use pyo3::prelude::{PyAnyMethods, PyBytesMethods, PyDictMethods, PyListMethods, PyStringMethods};
use pyo3::types::{PyBytes, PyDict, PyList, PyString};
use pyo3::{Bound, FromPyObject, IntoPyObject, IntoPyObjectExt, PyAny, PyErr, PyResult, Python};
use pythonize::depythonize;
use serde_json::Value;
#[repr(transparent)]
@@ -46,3 +48,24 @@ impl<'py> IntoPyObject<'py> for PyValue {
value_to_object(py, &self.0)
}
}
impl<'py> FromPyObject<'py> for PyValue {
fn extract_bound(ob: &Bound<'py, PyAny>) -> PyResult<Self> {
if let Ok(s) = ob.downcast::<PyString>() {
let str_slice = s.to_str()?;
let var = serde_json::from_str(str_slice).context("Invalid JSON")?;
return Ok(PyValue(var));
}
if let Ok(b) = ob.downcast::<PyBytes>() {
let bytes = b.as_bytes();
let var = serde_json::from_slice(bytes).context("Invalid JSON")?;
return Ok(PyValue(var));
}
let var = depythonize(ob)?;
Ok(PyValue(var))
}
}