Skip to content

Commit cdfe56e

Browse files
committed
Remove useless iterations
1 parent a46fad1 commit cdfe56e

File tree

1 file changed

+18
-9
lines changed

1 file changed

+18
-9
lines changed

jsonpatch.py

Lines changed: 18 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -39,7 +39,6 @@
3939
import functools
4040
import inspect
4141
import json
42-
import operator
4342
import sys
4443

4544
from jsonpointer import JsonPointer, JsonPointerException
@@ -52,6 +51,11 @@
5251

5352
if sys.version_info >= (3, 0):
5453
basestring = (bytes, str) # pylint: disable=C0103
54+
# pylint: disable=E0611
55+
from itertools import zip_longest
56+
else:
57+
# pylint: disable=E0611,W0404
58+
from itertools import izip_longest as zip_longest
5559

5660

5761
class JsonPatchException(Exception):
@@ -78,11 +82,11 @@ def multidict(ordered_pairs):
7882
for key, value in ordered_pairs:
7983
mdict[key].append(value)
8084

81-
# unpack lists that have only 1 item
82-
for key, values in mdict.items():
83-
if len(values) == 1:
84-
mdict[key] = values[0]
85-
return dict(mdict)
85+
return dict(
86+
# unpack lists that have only 1 item
87+
(key, values[0] if len(values) == 1 else values)
88+
for key, values in mdict.items()
89+
)
8690

8791

8892
def get_loadjson():
@@ -237,8 +241,12 @@ def __eq__(self, other):
237241
if not isinstance(other, JsonPatch):
238242
return False
239243

240-
return len(list(self._ops)) == len(list(other._ops)) and \
241-
all(map(operator.eq, self._ops, other._ops))
244+
for lop, rop in zip_longest(self._ops, other._ops):
245+
if lop is None or rop is None:
246+
return False
247+
if lop != rop:
248+
return False
249+
return True
242250

243251
@classmethod
244252
def from_string(cls, patch_str):
@@ -312,7 +320,8 @@ def compare_list(path, src, dst):
312320
'path': '/'.join(current),
313321
'value': dst[idx]}
314322
elif lsrc > ldst:
315-
for idx in reversed(range(ldst, lsrc)):
323+
# more effective than reversed(range(ldst, lsrc))
324+
for idx in range(lsrc - 1, ldst - 1 , -1):
316325
yield {'op': 'remove', 'path': '/'.join(path + [str(idx)])}
317326

318327
return cls(list(compare_dict([''], src, dst)))

0 commit comments

Comments
 (0)