Add __bool__ (__nonzero__) and __iter__ methods to JsonPatch.

This commit is contained in:
Alexander Shorin
2012-06-16 23:53:46 +04:00
parent be9be6d963
commit 495fa43116

View File

@@ -166,6 +166,33 @@ class JsonPatch(object):
>>> doc = {} >>> doc = {}
>>> patch.apply(doc) >>> patch.apply(doc)
{'foo': 'bar', 'baz': [42]} {'foo': 'bar', 'baz': [42]}
JsonPatch object is iterable, so you could easily access to each patch
statement in loop:
>>> lpatch = list(patch)
>>> lpatch[0]
{'add': '/foo', 'value': 'bar'}
Also JsonPatch could be converted directly to bool if it contains any
statements:
>>> bool(patch)
True
>>> bool(JsonPatch([]))
False
This behavior is very handy with :func:`make_patch` to write more readable
code:
>>> src = {'foo': 'bar', 'numbers': [1, 3, 4, 8]}
>>> dst = {'baz': 'qux', 'numbers': [1, 4, 7]}
>>> patch = make_patch(src, dst)
>>> if patch:
... # document have changed, do something useful
... pass
Instead of:
>>> if patch.patch:
... pass
""" """
def __init__(self, patch): def __init__(self, patch):
@@ -183,6 +210,14 @@ class JsonPatch(object):
"""str(self) -> self.to_string()""" """str(self) -> self.to_string()"""
return self.to_string() return self.to_string()
def __bool__(self):
return bool(self.patch)
__nonzero__ = __bool__
def __iter__(self):
return iter(self.patch)
@classmethod @classmethod
def from_string(cls, patch_str): def from_string(cls, patch_str):
"""Creates JsonPatch instance from string source.""" """Creates JsonPatch instance from string source."""