summaryrefslogtreecommitdiff
path: root/jsonpatch.py
diff options
context:
space:
mode:
authorAlexander Shorin <kxepal@gmail.com>2012-06-16 23:53:46 +0400
committerAlexander Shorin <kxepal@gmail.com>2012-06-16 23:53:46 +0400
commit495fa431166d378fce83ee65206f4947cfa3b525 (patch)
treefe9649bfd7e52eb06b1bb08551547fb86f54f976 /jsonpatch.py
parentbe9be6d96366c899cb0793e6502a40ccaca57473 (diff)
downloadpython-json-patch-495fa431166d378fce83ee65206f4947cfa3b525.tar.gz
Add __bool__ (__nonzero__) and __iter__ methods to JsonPatch.
Diffstat (limited to 'jsonpatch.py')
-rw-r--r--jsonpatch.py35
1 files changed, 35 insertions, 0 deletions
diff --git a/jsonpatch.py b/jsonpatch.py
index b93a14f..62293d7 100644
--- a/jsonpatch.py
+++ b/jsonpatch.py
@@ -166,6 +166,33 @@ class JsonPatch(object):
>>> doc = {}
>>> patch.apply(doc)
{'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):
@@ -183,6 +210,14 @@ class JsonPatch(object):
"""str(self) -> self.to_string()"""
return self.to_string()
+ def __bool__(self):
+ return bool(self.patch)
+
+ __nonzero__ = __bool__
+
+ def __iter__(self):
+ return iter(self.patch)
+
@classmethod
def from_string(cls, patch_str):
"""Creates JsonPatch instance from string source."""