Skip to content

Updated pythonize and pyo3 #401

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 5 commits into from
May 5, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
106 changes: 21 additions & 85 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 2 additions & 2 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -19,10 +19,10 @@ chrono = "0.4.40"
tantivy = "0.24.0"
itertools = "0.14.0"
futures = "0.3.31"
pythonize = "0.21.0"
pythonize = "0.24.0"
serde = "1.0"
serde_json = "1.0.140"

[dependencies.pyo3]
version = "0.21.0"
version = "0.24.2"
features = ["chrono", "extension-module"]
71 changes: 62 additions & 9 deletions src/document.rs
Original file line number Diff line number Diff line change
Expand Up @@ -52,9 +52,8 @@ pub(crate) fn extract_value(any: &Bound<PyAny>) -> PyResult<Value> {
return Ok(Value::Bytes(b));
}
if let Ok(dict) = any.downcast::<PyDict>() {
if let Ok(json_dict) = pythonize::depythonize_bound::<
BTreeMap<String, Value>,
>(dict.clone().into_any())
if let Ok(json_dict) =
pythonize::depythonize::<BTreeMap<String, Value>>(&dict.as_ref())
{
return Ok(Value::Object(json_dict.into_iter().collect()));
} else {
Expand Down Expand Up @@ -136,8 +135,8 @@ pub(crate) fn extract_value_for_type(
let dict = any
.downcast::<PyDict>()
.map_err(to_pyerr_for_type("Json", field_name, any))?;
let map = pythonize::depythonize_bound::<BTreeMap<String, Value>>(
dict.clone().into_any(),
let map = pythonize::depythonize::<BTreeMap<String, Value>>(
&dict.as_ref(),
)?;
Value::Object(map.into_iter().collect())
}
Expand Down Expand Up @@ -312,6 +311,60 @@ where
i64::deserialize(deserializer).map(tv::DateTime::from_timestamp_nanos)
}

fn deserialize_json_object_as_i64<'de, D>(
deserializer: D,
) -> Result<Vec<(String, Value)>, D::Error>
where
D: Deserializer<'de>,
{
let raw_object = Vec::deserialize(deserializer)?;
let converted_object = raw_object
.into_iter()
.map(|(key, value)| {
let converted_value = match value {
serde_json::Value::Number(num) => {
if let Some(i) = num.as_i64() {
Value::I64(i)
} else {
Value::F64(num.as_f64().unwrap())
}
}
serde_json::Value::Object(obj) => {
Value::Object(deserialize_json_object_as_i64_inner(obj))
}
_ => Value::from(value),
};
(key, converted_value)
})
.collect();

Ok(converted_object)
}

fn deserialize_json_object_as_i64_inner(
raw_object: serde_json::Map<String, serde_json::Value>,
) -> Vec<(String, Value)> {
raw_object
.into_iter()
.map(|(key, value)| {
let converted_value = match value {
serde_json::Value::Number(num) => {
if let Some(i) = num.as_i64() {
Value::I64(i)
} else {
Value::F64(num.as_f64().unwrap())
}
}
serde_json::Value::Object(obj) => {
Value::Object(deserialize_json_object_as_i64_inner(obj))
}
_ => Value::from(value),
};
(key, converted_value)
})
.collect()
}

/// An equivalent type to [`tantivy::schema::Value`], but unlike the tantivy crate's serialization
/// implementation, it uses tagging in its serialization and deserialization to differentiate
/// between different integer types.
Expand Down Expand Up @@ -347,6 +400,7 @@ enum SerdeValue {
/// Array
Array(Vec<Value>),
/// Object value.
#[serde(deserialize_with = "deserialize_json_object_as_i64")]
Object(Vec<(String, Value)>),
/// IpV6 Address. Internally there is no IpV4, it needs to be converted to `Ipv6Addr`.
IpAddr(Ipv6Addr),
Expand Down Expand Up @@ -581,6 +635,7 @@ impl Document {
}

#[staticmethod]
#[pyo3(signature = (py_dict, schema=None))]
fn from_dict(
py_dict: &Bound<PyDict>,
schema: Option<&Schema>,
Expand Down Expand Up @@ -719,9 +774,7 @@ impl Document {
serde_json::from_str(json_str).map_err(to_pyerr)?;
self.add_value(field_name, json_map);
Ok(())
} else if let Ok(json_map) =
pythonize::depythonize_bound::<JsonMap>(value.clone())
{
} else if let Ok(json_map) = pythonize::depythonize::<JsonMap>(value) {
self.add_value(field_name, json_map);
Ok(())
} else {
Expand Down Expand Up @@ -826,7 +879,7 @@ impl Document {

#[staticmethod]
fn _internal_from_pythonized(serialized: &Bound<PyAny>) -> PyResult<Self> {
pythonize::depythonize_bound(serialized.clone()).map_err(to_pyerr)
pythonize::depythonize(&serialized).map_err(to_pyerr)
}

fn __reduce__<'a>(
Expand Down
7 changes: 3 additions & 4 deletions src/query.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,10 +15,8 @@ use tantivy as tv;
struct OccurQueryPair(Occur, Query);

impl<'source> FromPyObject<'source> for OccurQueryPair {
fn extract(ob: &'source PyAny) -> PyResult<Self> {
let tuple = ob.downcast::<PyTuple>()?;
let occur = tuple.get_item(0)?.extract()?;
let query = tuple.get_item(1)?.extract()?;
fn extract_bound(ob: &Bound<'source, PyAny>) -> PyResult<Self> {
let (occur, query): (Occur, Query) = ob.extract()?;

Ok(OccurQueryPair(occur, query))
}
Expand Down Expand Up @@ -223,6 +221,7 @@ impl Query {

/// Construct a Tantivy's DisjunctionMaxQuery
#[staticmethod]
#[pyo3(signature = (subqueries, tie_breaker=None))]
pub(crate) fn disjunction_max_query(
subqueries: Vec<Query>,
tie_breaker: Option<Bound<PyFloat>>,
Expand Down
2 changes: 1 addition & 1 deletion src/schema.rs
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ impl Schema {

#[staticmethod]
fn _internal_from_pythonized(serialized: &Bound<PyAny>) -> PyResult<Self> {
pythonize::depythonize_bound(serialized.clone()).map_err(to_pyerr)
pythonize::depythonize(&serialized).map_err(to_pyerr)
}

fn __reduce__<'a>(
Expand Down