turbodiff 1.3.6

Rust-powered DeepDiff core
Documentation
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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
use crate::engine::canonical_string;
use crate::options::{DeepDiffOptions, PrettyOptions, ValueType};
use crate::DeepDiff;
use pyo3::exceptions::{PyTypeError, PyValueError};
use pyo3::prelude::*;
use pyo3::types::{PyAny, PyBytes, PyDict, PyFrozenSet, PyList, PySet, PyTuple, PyType};
use serde_json::Value;

#[pyclass(name = "DeepDiff")]
struct PyDeepDiff {
    inner: DeepDiff,
}

#[pymethods]
impl PyDeepDiff {
    #[new]
    #[pyo3(signature = (t1, t2, **kwargs))]
    fn new(
        t1: &Bound<'_, PyAny>,
        t2: &Bound<'_, PyAny>,
        kwargs: Option<&Bound<'_, PyDict>>,
    ) -> PyResult<Self> {
        let t1_val = value_from_py(t1)?;
        let t2_val = value_from_py(t2)?;
        let options = options_from_kwargs(kwargs)?;
        Ok(Self {
            inner: DeepDiff::with_options(t1_val, t2_val, options),
        })
    }

    fn to_dict(&self, py: Python<'_>) -> PyResult<PyObject> {
        value_to_py(py, &self.inner.to_value())
    }

    fn __repr__(&self, py: Python<'_>) -> PyResult<String> {
        let value = value_to_py(py, &self.inner.to_value())?;
        Ok(format!("DeepDiff({})", value.bind(py).repr()?))
    }

    fn __bool__(&self) -> bool {
        !self.inner.is_empty()
    }

    fn __len__(&self) -> usize {
        match &self.inner.to_value() {
            Value::Object(map) => map.len(),
            _ => 0,
        }
    }

    #[pyo3(signature = (*, compact = false, max_depth = 5, context = 0, no_color = false, path_header = false))]
    fn pretty(
        &self,
        compact: bool,
        max_depth: usize,
        context: usize,
        no_color: bool,
        path_header: bool,
    ) -> PyResult<String> {
        Ok(self.inner.pretty(PrettyOptions {
            compact,
            max_depth,
            context,
            no_color,
            path_header,
        }))
    }
}

pub(crate) fn register_module(m: &Bound<'_, PyModule>) -> PyResult<()> {
    m.add_class::<PyDeepDiff>()?;
    Ok(())
}

fn options_from_kwargs(kwargs: Option<&Bound<'_, PyDict>>) -> PyResult<DeepDiffOptions> {
    let mut options = DeepDiffOptions::default();

    if let Some(kwargs) = kwargs {
        for (key_any, value) in kwargs.iter() {
            let key: String = key_any.extract()?;
            match key {
                key if key == "ignore_order" => {
                    options = options.ignore_order(value.extract::<bool>()?);
                }
                key if key == "ignore_numeric_type_changes" => {
                    options = options.ignore_numeric_type_changes(value.extract::<bool>()?);
                }
                key if key == "ignore_string_type_changes" => {
                    options = options.ignore_string_type_changes(value.extract::<bool>()?);
                }
                key if key == "significant_digits" => {
                    if value.is_none() {
                        options = options.significant_digits(None);
                    } else {
                        options = options.significant_digits(Some(value.extract::<u32>()?));
                    }
                }
                key if key == "math_epsilon" => {
                    if value.is_none() {
                        options = options.math_epsilon(None);
                    } else {
                        options = options.math_epsilon(Some(value.extract::<f64>()?));
                    }
                }
                key if key == "math_absilon" => {
                    if value.is_none() {
                        options = options.math_epsilon(None);
                    } else {
                        options = options.math_epsilon(Some(value.extract::<f64>()?));
                    }
                }
                key if key == "atol" => {
                    if value.is_none() {
                        options = options.atol(None);
                    } else {
                        options = options.atol(Some(value.extract::<f64>()?));
                    }
                }
                key if key == "rtol" => {
                    if value.is_none() {
                        options = options.rtol(None);
                    } else {
                        options = options.rtol(Some(value.extract::<f64>()?));
                    }
                }
                key if key == "include_paths" => {
                    let paths = extract_string_list(&value)?;
                    options = options.include_paths(paths);
                }
                key if key == "exclude_paths" => {
                    let paths = extract_string_list(&value)?;
                    options = options.exclude_paths(paths);
                }
                key if key == "verbose_level" => {
                    options = options.verbose_level(value.extract::<u8>()?);
                }
                key if key == "ignore_type_in_groups" => {
                    let (groups, ignore_numeric, ignore_string) = extract_type_groups(&value)?;
                    options.ignore_type_in_groups = groups;
                    if ignore_numeric {
                        options = options.ignore_numeric_type_changes(true);
                    }
                    if ignore_string {
                        options = options.ignore_string_type_changes(true);
                    }
                }
                _ => {
                    return Err(PyValueError::new_err(format!(
                        "Unsupported option: {}",
                        key
                    )));
                }
            }
        }
    }

    Ok(options)
}

fn extract_string_list(value: &Bound<'_, PyAny>) -> PyResult<Vec<String>> {
    if let Ok(list) = value.downcast::<PyList>() {
        list.iter().map(|item| item.extract::<String>()).collect()
    } else if let Ok(tuple) = value.downcast::<PyTuple>() {
        tuple.iter().map(|item| item.extract::<String>()).collect()
    } else if let Ok(set) = value.downcast::<PySet>() {
        set.iter().map(|item| item.extract::<String>()).collect()
    } else if let Ok(set) = value.downcast::<PyFrozenSet>() {
        set.iter().map(|item| item.extract::<String>()).collect()
    } else {
        Err(PyTypeError::new_err(
            "Expected a list, tuple, or set of strings",
        ))
    }
}

fn extract_type_groups(value: &Bound<'_, PyAny>) -> PyResult<(Vec<Vec<ValueType>>, bool, bool)> {
    let groups_any = if let Ok(list) = value.downcast::<PyList>() {
        list.iter().collect::<Vec<_>>()
    } else if let Ok(tuple) = value.downcast::<PyTuple>() {
        tuple.iter().collect::<Vec<_>>()
    } else {
        return Err(PyTypeError::new_err(
            "Expected a list or tuple of type groups",
        ));
    };

    let py = value.py();
    let type_int = py.get_type_bound::<pyo3::types::PyLong>();
    let type_float = py.get_type_bound::<pyo3::types::PyFloat>();
    let type_bool = py.get_type_bound::<pyo3::types::PyBool>();
    let type_str = py.get_type_bound::<pyo3::types::PyString>();
    let type_bytes = py.get_type_bound::<PyBytes>();
    let type_none = py.get_type_bound::<pyo3::types::PyNone>();
    let type_list = py.get_type_bound::<PyList>();
    let type_tuple = py.get_type_bound::<PyTuple>();
    let type_dict = py.get_type_bound::<PyDict>();
    let numbers_mod = py.import_bound("numbers")?;
    let number_obj = numbers_mod.getattr("Number")?;
    let number_type = number_obj.downcast::<PyType>()?;
    let numpy_mod = py.import_bound("numpy").ok();

    let mut groups: Vec<Vec<ValueType>> = Vec::new();
    let mut ignore_numeric = false;
    let mut ignore_string = false;

    for group_any in groups_any {
        let items = if let Ok(list) = group_any.downcast::<PyList>() {
            list.iter().collect::<Vec<_>>()
        } else if let Ok(tuple) = group_any.downcast::<PyTuple>() {
            tuple.iter().collect::<Vec<_>>()
        } else {
            return Err(PyTypeError::new_err(
                "Each ignore_type_in_groups entry must be a list or tuple of types",
            ));
        };

        let mut group: Vec<ValueType> = Vec::new();
        let mut has_int = false;
        let mut has_float = false;
        let mut has_str = false;
        let mut has_bytes = false;

        for item in items {
            let ty = match item.downcast::<PyType>() {
                Ok(ty) => ty,
                Err(_) => {
                    let module: Option<String> = item
                        .getattr("__module__")
                        .ok()
                        .and_then(|m| m.extract().ok());
                    let name: Option<String> =
                        item.getattr("__name__").ok().and_then(|n| n.extract().ok());
                    if module.as_deref().unwrap_or("").starts_with("numpy")
                        && name.as_deref().unwrap_or("") == "array"
                    {
                        group.push(ValueType::Array);
                        continue;
                    }
                    return Err(PyTypeError::new_err(
                        "Unsupported type in ignore_type_in_groups",
                    ));
                }
            };
            let vt = if ty.is(&type_int) {
                has_int = true;
                ValueType::Number
            } else if ty.is(&type_float) {
                has_float = true;
                ValueType::Number
            } else if ty.is(&type_bool) {
                ValueType::Bool
            } else if ty.is(&type_str) {
                has_str = true;
                ValueType::String
            } else if ty.is(&type_bytes) {
                has_bytes = true;
                ValueType::String
            } else if ty.is(&type_none) {
                ValueType::Null
            } else if ty.is(&type_list) || ty.is(&type_tuple) {
                ValueType::Array
            } else if ty.is(&type_dict) {
                ValueType::Object
            } else if {
                let module: String = ty.getattr("__module__")?.extract()?;
                module.starts_with("numpy")
            } {
                let is_ndarray = if let Some(np) = numpy_mod.as_ref() {
                    if let Ok(ndarray) = np.getattr("ndarray") {
                        if let Ok(ndarray) = ndarray.downcast::<PyType>() {
                            ty.is_subclass(ndarray).unwrap_or(false)
                        } else {
                            false
                        }
                    } else {
                        false
                    }
                } else {
                    false
                };
                let name = ty.name()?.to_lowercase();
                if is_ndarray || name.contains("ndarray") {
                    ValueType::Array
                } else if name.contains("bool") {
                    ValueType::Bool
                } else {
                    if name.contains("float") || name.contains("floating") {
                        has_float = true;
                    } else if name.contains("int")
                        || name.contains("integer")
                        || name.contains("uint")
                        || name.contains("number")
                    {
                        has_int = true;
                    } else {
                        has_float = true;
                    }
                    ValueType::Number
                }
            } else if ty.is_subclass(number_type)? {
                let module: String = ty.getattr("__module__")?.extract()?;
                let name = ty.name()?.to_lowercase();
                if module == "numpy" {
                    if name.contains("float") || name.contains("floating") {
                        has_float = true;
                    } else if name.contains("int")
                        || name.contains("integer")
                        || name.contains("uint")
                    {
                        has_int = true;
                    } else {
                        has_float = true;
                    }
                } else {
                    has_float = true;
                }
                ValueType::Number
            } else {
                return Err(PyTypeError::new_err(
                    "Unsupported type in ignore_type_in_groups",
                ));
            };
            group.push(vt);
        }

        if has_int && has_float {
            ignore_numeric = true;
        }
        if has_str && has_bytes {
            ignore_string = true;
        }

        groups.push(group);
    }

    Ok((groups, ignore_numeric, ignore_string))
}

fn value_from_py(value: &Bound<'_, PyAny>) -> PyResult<Value> {
    if value.is_none() {
        return Ok(Value::Null);
    }
    if let Ok(b) = value.extract::<bool>() {
        return Ok(Value::Bool(b));
    }
    if let Ok(i) = value.extract::<i64>() {
        return Ok(Value::Number(i.into()));
    }
    if let Ok(u) = value.extract::<u64>() {
        return Ok(Value::Number(u.into()));
    }
    if let Ok(f) = value.extract::<f64>() {
        if let Some(num) = serde_json::Number::from_f64(f) {
            return Ok(Value::Number(num));
        }
        return Err(PyValueError::new_err("Float value is not finite"));
    }
    if let Ok(s) = value.extract::<String>() {
        return Ok(Value::String(s));
    }
    if let Ok(list) = value.downcast::<PyList>() {
        let mut items = Vec::with_capacity(list.len());
        for item in list.iter() {
            items.push(value_from_py(&item)?);
        }
        return Ok(Value::Array(items));
    }
    if let Ok(tuple) = value.downcast::<PyTuple>() {
        let mut items = Vec::with_capacity(tuple.len());
        for item in tuple.iter() {
            items.push(value_from_py(&item)?);
        }
        return Ok(Value::Array(items));
    }
    if let Ok(set) = value.downcast::<PySet>() {
        let mut items = Vec::with_capacity(set.len());
        for item in set.iter() {
            items.push(value_from_py(&item)?);
        }
        items.sort_by_key(canonical_string);
        return Ok(Value::Array(items));
    }
    if let Ok(set) = value.downcast::<PyFrozenSet>() {
        let mut items = Vec::with_capacity(set.len());
        for item in set.iter() {
            items.push(value_from_py(&item)?);
        }
        items.sort_by_key(canonical_string);
        return Ok(Value::Array(items));
    }
    if let Ok(dict) = value.downcast::<PyDict>() {
        let mut map = serde_json::Map::with_capacity(dict.len());
        for (k, v) in dict.iter() {
            let key: String = match k.extract::<String>() {
                Ok(val) => val,
                Err(_) => k
                    .str()
                    .and_then(|s| s.extract::<String>())
                    .map_err(|_| PyTypeError::new_err("Unsupported dict key type for DeepDiff"))?,
            };
            map.insert(key, value_from_py(&v)?);
        }
        return Ok(Value::Object(map));
    }
    if value
        .get_type()
        .getattr("__module__")?
        .extract::<String>()?
        .starts_with("pandas")
    {
        if let Ok(to_dict) = value.getattr("to_dict") {
            let py = value.py();
            let kwargs = PyDict::new_bound(py);
            kwargs.set_item("orient", "list")?;
            if let Ok(res) = to_dict.call((), Some(&kwargs)) {
                return value_from_py(&res);
            }
            let res = to_dict.call0()?;
            return value_from_py(&res);
        }
        if let Ok(to_numpy) = value.getattr("to_numpy") {
            let res = to_numpy.call0()?;
            return value_from_py(&res);
        }
    }
    if value.hasattr("model_dump")? {
        let py = value.py();
        let kwargs = PyDict::new_bound(py);
        kwargs.set_item("mode", "json")?;
        if let Ok(dumped) = value.call_method("model_dump", (), Some(&kwargs)) {
            return value_from_py(&dumped);
        }
        let dumped = value.call_method0("model_dump")?;
        return value_from_py(&dumped);
    }
    if value.hasattr("dict")? {
        let dumped = value.call_method0("dict")?;
        return value_from_py(&dumped);
    }
    if value
        .get_type()
        .getattr("__module__")?
        .extract::<String>()?
        .starts_with("numpy")
    {
        if let Ok(tolist) = value.call_method0("tolist") {
            return value_from_py(&tolist);
        }
    }

    Err(PyTypeError::new_err("Unsupported Python type for DeepDiff"))
}

fn value_to_py(py: Python<'_>, value: &Value) -> PyResult<PyObject> {
    match value {
        Value::Null => Ok(py.None()),
        Value::Bool(b) => Ok(b.into_py(py)),
        Value::Number(n) => {
            if let Some(i) = n.as_i64() {
                Ok(i.into_py(py))
            } else if let Some(u) = n.as_u64() {
                Ok(u.into_py(py))
            } else if let Some(f) = n.as_f64() {
                Ok(f.into_py(py))
            } else {
                Err(PyValueError::new_err("Invalid number"))
            }
        }
        Value::String(s) => Ok(s.into_py(py)),
        Value::Array(arr) => {
            let list = PyList::empty_bound(py);
            for item in arr {
                list.append(value_to_py(py, item)?)?;
            }
            Ok(list.into_py(py))
        }
        Value::Object(obj) => {
            let dict = PyDict::new_bound(py);
            for (k, v) in obj {
                dict.set_item(k, value_to_py(py, v)?)?;
            }
            Ok(dict.into_py(py))
        }
    }
}