Skip to content

Commit a46fad1

Browse files
committed
Raise pylint score from 6.87 to 9.10
1 parent 07667c6 commit a46fad1

File tree

1 file changed

+62
-51
lines changed

1 file changed

+62
-51
lines changed

jsonpatch.py

Lines changed: 62 additions & 51 deletions
Original file line numberDiff line numberDiff line change
@@ -30,31 +30,30 @@
3030
# THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
3131
#
3232

33+
""" Apply JSON-Patches (RFC 6902) """
34+
3335
from __future__ import unicode_literals
3436

35-
""" Apply JSON-Patches (RFC 6902) """
37+
import collections
38+
import copy
39+
import functools
40+
import inspect
41+
import json
42+
import operator
43+
import sys
44+
45+
from jsonpointer import JsonPointer, JsonPointerException
3646

3747
# Will be parsed by setup.py to determine package metadata
3848
__author__ = 'Stefan Kögl <[email protected]>'
3949
__version__ = '1.3'
4050
__website__ = 'https://github.com/stefankoegl/python-json-patch'
4151
__license__ = 'Modified BSD License'
4252

43-
import copy
44-
import sys
45-
import operator
46-
import collections
47-
48-
import json
49-
50-
import jsonpointer
51-
5253
if sys.version_info >= (3, 0):
53-
basestring = (bytes, str)
54+
basestring = (bytes, str) # pylint: disable=C0103
5455

5556

56-
JsonPointerException = jsonpointer.JsonPointerException
57-
5857
class JsonPatchException(Exception):
5958
"""Base Json Patch exception"""
6059

@@ -67,22 +66,23 @@ class JsonPatchConflict(JsonPatchException):
6766
- etc.
6867
"""
6968

69+
7070
class JsonPatchTestFailed(JsonPatchException, AssertionError):
7171
""" A Test operation failed """
7272

7373

7474
def multidict(ordered_pairs):
7575
"""Convert duplicate keys values to lists."""
7676
# read all values into lists
77-
d = collections.defaultdict(list)
78-
for k, v in ordered_pairs:
79-
d[k].append(v)
77+
mdict = collections.defaultdict(list)
78+
for key, value in ordered_pairs:
79+
mdict[key].append(value)
8080

8181
# unpack lists that have only 1 item
82-
for k, v in d.items():
83-
if len(v) == 1:
84-
d[k] = v[0]
85-
return dict(d)
82+
for key, values in mdict.items():
83+
if len(values) == 1:
84+
mdict[key] = values[0]
85+
return dict(mdict)
8686

8787

8888
def get_loadjson():
@@ -94,9 +94,6 @@ def get_loadjson():
9494
function with object_pairs_hook set to multidict for Python versions that
9595
support the parameter. """
9696

97-
import inspect
98-
import functools
99-
10097
argspec = inspect.getargspec(json.load)
10198
if 'object_pairs_hook' not in argspec.args:
10299
return json.load
@@ -123,12 +120,14 @@ def apply_patch(doc, patch, in_place=False):
123120
:rtype: dict
124121
125122
>>> doc = {'foo': 'bar'}
126-
>>> other = apply_patch(doc, [{'op': 'add', 'path': '/baz', 'value': 'qux'}])
123+
>>> patch = [{'op': 'add', 'path': '/baz', 'value': 'qux'}]
124+
>>> other = apply_patch(doc, patch)
127125
>>> doc is not other
128126
True
129127
>>> other == {'foo': 'bar', 'baz': 'qux'}
130128
True
131-
>>> apply_patch(doc, [{'op': 'add', 'path': '/baz', 'value': 'qux'}], in_place=True) == {'foo': 'bar', 'baz': 'qux'}
129+
>>> patch = [{'op': 'add', 'path': '/baz', 'value': 'qux'}]
130+
>>> apply_patch(doc, patch, in_place=True) == {'foo': 'bar', 'baz': 'qux'}
132131
True
133132
>>> doc == other
134133
True
@@ -140,6 +139,7 @@ def apply_patch(doc, patch, in_place=False):
140139
patch = JsonPatch(patch)
141140
return patch.apply(doc, in_place)
142141

142+
143143
def make_patch(src, dst):
144144
"""Generates patch by comparing of two document objects. Actually is
145145
a proxy to :meth:`JsonPatch.from_diff` method.
@@ -230,19 +230,16 @@ def __bool__(self):
230230
def __iter__(self):
231231
return iter(self.patch)
232232

233-
234233
def __hash__(self):
235234
return hash(tuple(self._ops))
236235

237-
238236
def __eq__(self, other):
239237
if not isinstance(other, JsonPatch):
240238
return False
241239

242240
return len(list(self._ops)) == len(list(other._ops)) and \
243241
all(map(operator.eq, self._ops, other._ops))
244242

245-
246243
@classmethod
247244
def from_string(cls, patch_str):
248245
"""Creates JsonPatch instance from string source.
@@ -298,7 +295,9 @@ def compare_dict(path, src, dst):
298295
yield operation
299296
for key in dst:
300297
if key not in src:
301-
yield {'op': 'add', 'path': '/'.join(path + [key]), 'value': dst[key]}
298+
yield {'op': 'add',
299+
'path': '/'.join(path + [key]),
300+
'value': dst[key]}
302301

303302
def compare_list(path, src, dst):
304303
lsrc, ldst = len(src), len(dst)
@@ -309,7 +308,9 @@ def compare_list(path, src, dst):
309308
if lsrc < ldst:
310309
for idx in range(lsrc, ldst):
311310
current = path + [str(idx)]
312-
yield {'op': 'add', 'path': '/'.join(current), 'value': dst[idx]}
311+
yield {'op': 'add',
312+
'path': '/'.join(current),
313+
'value': dst[idx]}
313314
elif lsrc > ldst:
314315
for idx in reversed(range(ldst, lsrc)):
315316
yield {'op': 'remove', 'path': '/'.join(path + [str(idx)])}
@@ -361,28 +362,24 @@ def _get_operation(self, operation):
361362
return cls(operation)
362363

363364

364-
365365
class PatchOperation(object):
366366
"""A single operation inside a JSON Patch."""
367367

368368
def __init__(self, operation):
369369
self.location = operation['path']
370-
self.pointer = jsonpointer.JsonPointer(self.location)
370+
self.pointer = JsonPointer(self.location)
371371
self.operation = operation
372372

373373
def apply(self, obj):
374374
"""Abstract method that applies patch operation to specified object."""
375375
raise NotImplementedError('should implement patch operation.')
376376

377-
378377
def __hash__(self):
379378
return hash(frozenset(self.operation.items()))
380379

381-
382380
def __eq__(self, other):
383381
if not isinstance(other, PatchOperation):
384382
return False
385-
386383
return self.operation == other.operation
387384

388385

@@ -409,24 +406,22 @@ def apply(self, obj):
409406
# type is already checked in to_last(), so we assert here
410407
# for consistency
411408
assert isinstance(subobj, list) or isinstance(subobj, dict), \
412-
"invalid document type %s" (type(doc),)
409+
"invalid document type %s" % type(subobj)
413410

414411
if isinstance(subobj, list):
415412

416413
if part == '-':
417-
subobj.append(value)
414+
subobj.append(value) # pylint: disable=E1103
418415

419416
elif part > len(subobj) or part < 0:
420417
raise JsonPatchConflict("can't insert outside of list")
421418

422419
else:
423-
subobj.insert(part, value)
420+
subobj.insert(part, value) # pylint: disable=E1103
424421

425422
elif isinstance(subobj, dict):
426423
if part is None:
427-
# we're replacing the root
428-
obj = value
429-
424+
obj = value # we're replacing the root
430425
else:
431426
subobj[part] = value
432427

@@ -443,7 +438,7 @@ def apply(self, obj):
443438
# type is already checked in to_last(), so we assert here
444439
# for consistency
445440
assert isinstance(subobj, list) or isinstance(subobj, dict), \
446-
"invalid document type %s" (type(doc),)
441+
"invalid document type %s" % subobj
447442

448443
if part is None:
449444
return value
@@ -454,8 +449,8 @@ def apply(self, obj):
454449

455450
elif isinstance(subobj, dict):
456451
if not part in subobj:
457-
raise JsonPatchConflict("can't replace non-existant object '%s'"
458-
"" % part)
452+
raise JsonPatchConflict("can't replace non-existent object '%s'"
453+
% part)
459454

460455
subobj[part] = value
461456
return obj
@@ -465,15 +460,24 @@ class MoveOperation(PatchOperation):
465460
"""Moves an object property or an array element to new location."""
466461

467462
def apply(self, obj):
468-
from_ptr = jsonpointer.JsonPointer(self.operation['from'])
463+
from_ptr = JsonPointer(self.operation['from'])
469464
subobj, part = from_ptr.to_last(obj)
470465
value = subobj[part]
471466

472467
if self.pointer.contains(from_ptr):
473468
raise JsonPatchException('Cannot move values into its own children')
474469

475-
obj = RemoveOperation({'op': 'remove', 'path': self.operation['from']}).apply(obj)
476-
obj = AddOperation({'op': 'add', 'path': self.location, 'value': value}).apply(obj)
470+
obj = RemoveOperation({
471+
'op': 'remove',
472+
'path': self.operation['from']
473+
}).apply(obj)
474+
475+
obj = AddOperation({
476+
'op': 'add',
477+
'path': self.location,
478+
'value': value
479+
}).apply(obj)
480+
477481
return obj
478482

479483

@@ -487,14 +491,15 @@ def apply(self, obj):
487491
val = subobj
488492
else:
489493
val = self.pointer.walk(subobj, part)
490-
491494
except JsonPointerException as ex:
492495
raise JsonPatchTestFailed(str(ex))
493496

494497
if 'value' in self.operation:
495498
value = self.operation['value']
496499
if val != value:
497-
raise JsonPatchTestFailed('%s is not equal to tested value %s (types %s and %s)' % (val, value, type(val), type(value)))
500+
raise JsonPatchTestFailed(
501+
'%s is not equal to tested value %s (types %s and %s)'
502+
% (val, value, type(val), type(value)))
498503

499504
return obj
500505

@@ -503,8 +508,14 @@ class CopyOperation(PatchOperation):
503508
""" Copies an object property or an array element to a new location """
504509

505510
def apply(self, obj):
506-
from_ptr = jsonpointer.JsonPointer(self.operation['from'])
511+
from_ptr = JsonPointer(self.operation['from'])
507512
subobj, part = from_ptr.to_last(obj)
508513
value = copy.deepcopy(subobj[part])
509-
obj = AddOperation({'op': 'add', 'path': self.location, 'value': value}).apply(obj)
514+
515+
obj = AddOperation({
516+
'op': 'add',
517+
'path': self.location,
518+
'value': value
519+
}).apply(obj)
520+
510521
return obj

0 commit comments

Comments
 (0)