Skip to content

Commit 661c3b9

Browse files
committed
fixing some types based on pyright report
1 parent a7b4a45 commit 661c3b9

File tree

4 files changed

+60
-57
lines changed

4 files changed

+60
-57
lines changed

deepdiff/diff.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@
1818
from inspect import getmembers
1919
from itertools import zip_longest
2020
from functools import lru_cache
21-
from deepdiff.helper import (strings, bytes_type, numbers, uuids, datetimes, ListItemRemovedOrAdded, notpresent,
21+
from deepdiff.helper import (strings, bytes_type, numbers, uuids, ListItemRemovedOrAdded, notpresent,
2222
IndexedHash, unprocessed, add_to_frozen_set, basic_types,
2323
convert_item_or_items_into_set_else_none, get_type,
2424
convert_item_or_items_into_compiled_regexes_else_none,

deepdiff/helper.py

Lines changed: 17 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -12,10 +12,7 @@
1212
from ast import literal_eval
1313
from decimal import Decimal, localcontext, InvalidOperation as InvalidDecimalOperation
1414
from itertools import repeat
15-
# from orderly_set import OrderlySet as SetOrderedBase # median: 0.806 s, some tests are failing
16-
# from orderly_set import SetOrdered as SetOrderedBase # median 1.011 s, didn't work for tests
1715
from orderly_set import StableSetEq as SetOrderedBase # median: 1.0867 s for cache test, 5.63s for all tests
18-
# from orderly_set import OrderedSet as SetOrderedBase # median 1.1256 s for cache test, 5.63s for all tests
1916
from threading import Timer
2017

2118

@@ -91,14 +88,14 @@ def __repr__(self):
9188
)
9289

9390
numpy_dtypes = set(numpy_numbers)
94-
numpy_dtypes.add(np_bool_)
91+
numpy_dtypes.add(np_bool_) # type: ignore
9592

9693
numpy_dtype_str_to_type = {
9794
item.__name__: item for item in numpy_dtypes
9895
}
9996

10097
try:
101-
from pydantic.main import BaseModel as PydanticBaseModel
98+
from pydantic.main import BaseModel as PydanticBaseModel # type: ignore
10299
except ImportError:
103100
PydanticBaseModel = pydantic_base_model_type
104101

@@ -367,7 +364,7 @@ def get_type(obj):
367364
Get the type of object or if it is a class, return the class itself.
368365
"""
369366
if isinstance(obj, np_ndarray):
370-
return obj.dtype.type
367+
return obj.dtype.type # type: ignore
371368
return obj if type(obj) is type else type(obj)
372369

373370

@@ -409,7 +406,7 @@ def number_to_string(number, significant_digits, number_format_notation="f"):
409406
except KeyError:
410407
raise ValueError("number_format_notation got invalid value of {}. The valid values are 'f' and 'e'".format(number_format_notation)) from None
411408

412-
if not isinstance(number, numbers):
409+
if not isinstance(number, numbers): # type: ignore
413410
return number
414411
elif isinstance(number, Decimal):
415412
with localcontext() as ctx:
@@ -423,32 +420,31 @@ def number_to_string(number, significant_digits, number_format_notation="f"):
423420
# For example '999.99999999' will become '1000.000000' after quantize
424421
ctx.prec += 1
425422
number = number.quantize(Decimal('0.' + '0' * significant_digits))
426-
elif isinstance(number, only_complex_number):
423+
elif isinstance(number, only_complex_number): # type: ignore
427424
# Case for complex numbers.
428425
number = number.__class__(
429-
"{real}+{imag}j".format(
426+
"{real}+{imag}j".format( # type: ignore
430427
real=number_to_string(
431-
number=number.real,
428+
number=number.real, # type: ignore
432429
significant_digits=significant_digits,
433430
number_format_notation=number_format_notation
434431
),
435432
imag=number_to_string(
436-
number=number.imag,
433+
number=number.imag, # type: ignore
437434
significant_digits=significant_digits,
438435
number_format_notation=number_format_notation
439436
)
440-
)
437+
) # type: ignore
441438
)
442439
else:
443-
# import pytest; pytest.set_trace()
444-
number = round(number=number, ndigits=significant_digits)
440+
number = round(number=number, ndigits=significant_digits) # type: ignore
445441

446442
if significant_digits == 0:
447443
number = int(number)
448444

449445
if number == 0.0:
450446
# Special case for 0: "-0.xx" should compare equal to "0.xx"
451-
number = abs(number)
447+
number = abs(number) # type: ignore
452448

453449
# Cast number to string
454450
result = (using % significant_digits).format(number)
@@ -565,7 +561,8 @@ def start(self):
565561

566562
def stop(self):
567563
duration = self._get_duration_sec()
568-
self._timer.cancel()
564+
if self._timer is not None:
565+
self._timer.cancel()
569566
self.is_running = False
570567
return duration
571568

@@ -661,8 +658,8 @@ def cartesian_product_numpy(*arrays):
661658
https://stackoverflow.com/a/49445693/1497443
662659
"""
663660
la = len(arrays)
664-
dtype = np.result_type(*arrays)
665-
arr = np.empty((la, *map(len, arrays)), dtype=dtype)
661+
dtype = np.result_type(*arrays) # type: ignore
662+
arr = np.empty((la, *map(len, arrays)), dtype=dtype) # type: ignore
666663
idx = slice(None), *repeat(None, la)
667664
for i, a in enumerate(arrays):
668665
arr[i, ...] = a[idx[:la - i]]
@@ -676,7 +673,7 @@ def diff_numpy_array(A, B):
676673
By Divakar
677674
https://stackoverflow.com/a/52417967/1497443
678675
"""
679-
return A[~np.isin(A, B)]
676+
return A[~np.isin(A, B)] # type: ignore
680677

681678

682679
PYTHON_TYPE_TO_NUMPY_TYPE = {
@@ -754,7 +751,7 @@ class OpcodeTag(EnumBase):
754751
insert = 'insert'
755752
delete = 'delete'
756753
equal = 'equal'
757-
replace = 'replace'
754+
replace = 'replace' # type: ignore
758755
# swapped = 'swapped' # in the future we should support reporting of items swapped with each other
759756

760757

deepdiff/model.py

Lines changed: 20 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -62,24 +62,26 @@ def mutual_add_removes_to_become_value_changes(self):
6262
6363
This function should only be run on the Tree Result.
6464
"""
65-
if self.get('iterable_item_added') and self.get('iterable_item_removed'):
66-
added_paths = {i.path(): i for i in self['iterable_item_added']}
67-
removed_paths = {i.path(): i for i in self['iterable_item_removed']}
65+
iterable_item_added = self.get('iterable_item_added')
66+
iterable_item_removed = self.get('iterable_item_removed')
67+
if iterable_item_added is not None and iterable_item_removed is not None:
68+
added_paths = {i.path(): i for i in iterable_item_added}
69+
removed_paths = {i.path(): i for i in iterable_item_removed}
6870
mutual_paths = set(added_paths) & set(removed_paths)
6971

70-
if mutual_paths and 'values_changed' not in self:
72+
if mutual_paths and 'values_changed' not in self or self['values_changed'] is None:
7173
self['values_changed'] = SetOrdered()
7274
for path in mutual_paths:
7375
level_before = removed_paths[path]
74-
self['iterable_item_removed'].remove(level_before)
76+
iterable_item_removed.remove(level_before)
7577
level_after = added_paths[path]
76-
self['iterable_item_added'].remove(level_after)
78+
iterable_item_added.remove(level_after)
7779
level_before.t2 = level_after.t2
78-
self['values_changed'].add(level_before)
80+
self['values_changed'].add(level_before) # type: ignore
7981
level_before.report_type = 'values_changed'
80-
if 'iterable_item_removed' in self and not self['iterable_item_removed']:
82+
if 'iterable_item_removed' in self and not iterable_item_removed:
8183
del self['iterable_item_removed']
82-
if 'iterable_item_added' in self and not self['iterable_item_added']:
84+
if 'iterable_item_added' in self and not iterable_item_added:
8385
del self['iterable_item_added']
8486

8587
def __getitem__(self, item):
@@ -242,7 +244,7 @@ def _from_tree_set_item_added_or_removed(self, tree, key):
242244
item = "'%s'" % item
243245
if is_dict:
244246
if path not in set_item_info:
245-
set_item_info[path] = set()
247+
set_item_info[path] = set() # type: ignore
246248
set_item_info[path].add(item)
247249
else:
248250
set_item_info.add("{}[{}]".format(path, str(item)))
@@ -619,12 +621,12 @@ def auto_generate_child_rel(self, klass, param, param2=None):
619621
:param param: A ChildRelationship subclass-dependent parameter describing how to get from parent to child,
620622
e.g. the key in a dict
621623
"""
622-
if self.down.t1 is not notpresent:
624+
if self.down.t1 is not notpresent: # type: ignore
623625
self.t1_child_rel = ChildRelationship.create(
624-
klass=klass, parent=self.t1, child=self.down.t1, param=param)
625-
if self.down.t2 is not notpresent:
626+
klass=klass, parent=self.t1, child=self.down.t1, param=param) # type: ignore
627+
if self.down.t2 is not notpresent: # type: ignore
626628
self.t2_child_rel = ChildRelationship.create(
627-
klass=klass, parent=self.t2, child=self.down.t2, param=param if param2 is None else param2)
629+
klass=klass, parent=self.t2, child=self.down.t2, param=param if param2 is None else param2) # type: ignore
628630

629631
@property
630632
def all_up(self):
@@ -739,15 +741,15 @@ def path(self, root="root", force=None, get_parent_too=False, use_t2=False, outp
739741
result = None
740742
break
741743
elif output_format == 'list':
742-
result.append(next_rel.param)
744+
result.append(next_rel.param) # type: ignore
743745

744746
# Prepare processing next level
745747
level = level.down
746748

747749
if output_format == 'str':
748750
if get_parent_too:
749-
self._path[cache_key] = (parent, param, result)
750-
output = (self._format_result(root, parent), param, self._format_result(root, result))
751+
self._path[cache_key] = (parent, param, result) # type: ignore
752+
output = (self._format_result(root, parent), param, self._format_result(root, result)) # type: ignore
751753
else:
752754
self._path[cache_key] = result
753755
output = self._format_result(root, result)
@@ -907,7 +909,7 @@ def stringify_param(self, force=None):
907909
elif isinstance(param, tuple): # Currently only for numpy ndarrays
908910
result = ']['.join(map(repr, param))
909911
elif hasattr(param, '__dataclass_fields__'):
910-
attrs_to_values = [f"{key}={value}" for key, value in [(i, getattr(param, i)) for i in param.__dataclass_fields__]]
912+
attrs_to_values = [f"{key}={value}" for key, value in [(i, getattr(param, i)) for i in param.__dataclass_fields__]] # type: ignore
911913
result = f"{param.__class__.__name__}({','.join(attrs_to_values)})"
912914
else:
913915
candidate = repr(param)

deepdiff/summarize.py

Lines changed: 22 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
from typing import Any
12
from deepdiff.serialization import json_dumps
23

34

@@ -13,22 +14,23 @@ def _truncate(s, max_len):
1314
return s[:max_len - 5] + "..." + s[-2:]
1415

1516
class JSONNode:
16-
def __init__(self, data, key=None):
17+
def __init__(self, data: Any, key=None):
1718
"""
1819
Build a tree node for the JSON data.
1920
If this node is a child of a dict, key is its key name.
2021
"""
2122
self.key = key
23+
self.children_list: list[JSONNode] = []
24+
self.children_dict: list[tuple[Any, JSONNode]] = []
2225
if isinstance(data, dict):
2326
self.type = "dict"
24-
self.children = []
2527
# Preserve insertion order: list of (key, child) pairs.
2628
for k, v in data.items():
2729
child = JSONNode(v, key=k)
28-
self.children.append((k, child))
30+
self.children_dict.append((k, child))
2931
elif isinstance(data, list):
3032
self.type = "list"
31-
self.children = [JSONNode(item) for item in data]
33+
self.children_list = [JSONNode(item) for item in data]
3234
else:
3335
self.type = "primitive"
3436
# For primitives, use json.dumps to get a compact representation.
@@ -37,24 +39,25 @@ def __init__(self, data, key=None):
3739
except Exception:
3840
self.value = str(data)
3941

40-
def full_repr(self):
42+
def full_repr(self) -> str:
4143
"""Return the full minimized JSON representation (without trimming) for this node."""
4244
if self.type == "primitive":
4345
return self.value
4446
elif self.type == "dict":
4547
parts = []
46-
for k, child in self.children:
48+
for k, child in self.children_dict:
4749
parts.append(f'"{k}":{child.full_repr()}')
4850
return "{" + ",".join(parts) + "}"
4951
elif self.type == "list":
50-
parts = [child.full_repr() for child in self.children]
52+
parts = [child.full_repr() for child in self.children_list]
5153
return "[" + ",".join(parts) + "]"
54+
return self.value
5255

5356
def full_weight(self):
5457
"""Return the character count of the full representation."""
5558
return len(self.full_repr())
5659

57-
def summarize(self, budget):
60+
def _summarize(self, budget) -> str:
5861
"""
5962
Return a summary string for this node that fits within budget characters.
6063
The algorithm may drop whole sub-branches (for dicts) or truncate long primitives.
@@ -69,16 +72,17 @@ def summarize(self, budget):
6972
return self._summarize_dict(budget)
7073
elif self.type == "list":
7174
return self._summarize_list(budget)
75+
return self.value
7276

73-
def _summarize_dict(self, budget):
77+
def _summarize_dict(self, budget) -> str:
7478
# If the dict is empty, return {}
75-
if not self.children:
79+
if not self.children_dict:
7680
return "{}"
7781
# Build a list of pairs with fixed parts:
7882
# Each pair: key_repr is f'"{key}":'
7983
# Also store the full (untrimmed) child representation.
8084
pairs = []
81-
for k, child in self.children:
85+
for k, child in self.children_dict:
8286
key_repr = f'"{k}":'
8387
child_full = child.full_repr()
8488
pair_full = key_repr + child_full
@@ -103,7 +107,7 @@ def _summarize_dict(self, budget):
103107
# Heuristic: while the representation is too long, drop the pair whose child_full is longest.
104108
while kept:
105109
# Sort kept pairs in original insertion order.
106-
kept_sorted = sorted(kept, key=lambda p: self.children.index((p["key"], p["child"])))
110+
kept_sorted = sorted(kept, key=lambda p: self.children_dict.index((p["key"], p["child"])))
107111
current_n = len(kept_sorted)
108112
fixed = sum(len(p["key_repr"]) for p in kept_sorted) + (current_n - 1) + 2
109113
remaining_budget = budget - fixed
@@ -116,7 +120,7 @@ def _summarize_dict(self, budget):
116120
child_summaries = []
117121
for p in kept_sorted:
118122
ideal = int(remaining_budget * (len(p["child_full"]) / total_child_full)) if total_child_full > 0 else 0
119-
summary_child = p["child"].summarize(ideal)
123+
summary_child = p["child"]._summarize(ideal)
120124
child_summaries.append(summary_child)
121125
candidate = "{" + ",".join([p["key_repr"] + s for p, s in zip(kept_sorted, child_summaries)]) + "}"
122126
if len(candidate) <= budget:
@@ -127,17 +131,17 @@ def _summarize_dict(self, budget):
127131
# If nothing remains, return a truncated empty object.
128132
return _truncate("{}", budget)
129133

130-
def _summarize_list(self, budget):
134+
def _summarize_list(self, budget) -> str:
131135
# If the list is empty, return []
132-
if not self.children:
136+
if not self.children_list:
133137
return "[]"
134138
full_repr = self.full_repr()
135139
if len(full_repr) <= budget:
136140
return full_repr
137141
# For lists, show only the first element and an omission indicator if more elements exist.
138-
suffix = ",..." if len(self.children) > 1 else ""
142+
suffix = ",..." if len(self.children_list) > 1 else ""
139143
inner_budget = budget - 2 - len(suffix) # subtract brackets and suffix
140-
first_summary = self.children[0].summarize(inner_budget)
144+
first_summary = self.children_list[0]._summarize(inner_budget)
141145
candidate = "[" + first_summary + suffix + "]"
142146
if len(candidate) <= budget:
143147
return candidate
@@ -150,4 +154,4 @@ def summarize(data, max_length=200):
150154
ensuring the final string is no longer than self.max_length.
151155
"""
152156
root = JSONNode(data)
153-
return root.summarize(max_length).replace("{,", "{")
157+
return root._summarize(max_length).replace("{,", "{")

0 commit comments

Comments
 (0)