diff --git a/doc/tutorial.rst b/doc/tutorial.rst index 5a58c4f..267f05c 100644 --- a/doc/tutorial.rst +++ b/doc/tutorial.rst @@ -87,3 +87,21 @@ same path on several objects. >>> obj2 = {'foo': {'0': 1, '1': 10, '2': 100}} >>> pointer.resolve(obj2) 10 + +Checking pointer prefixes +------------------------- + +``child.contains(parent)`` checks whether the parent's parts are a prefix of +the child's parts. The equivalent membership expression is ``parent in child``. +The comparison is between whole path parts, so ``/foo/b`` is not a prefix of +``/foo/bar``. Equal pointers and the root pointer are prefixes too: + + >>> from jsonpointer import JsonPointer + >>> parent = JsonPointer('/foo') + >>> child = JsonPointer('/foo/bar') + >>> child.contains(parent) + True + >>> parent in child + True + >>> child in parent + False diff --git a/jsonpointer.py b/jsonpointer.py index 8a31f19..e888616 100644 --- a/jsonpointer.py +++ b/jsonpointer.py @@ -349,11 +349,34 @@ def walk(self, doc, part): raise JsonPointerException("member '%s' not found" % (part,)) def contains(self, ptr): - """ Returns True if self contains the given ptr """ + """Returns True if ptr's parts are a prefix of this pointer's parts. + + Equal pointers and the root pointer are also prefixes. For example, + the longer pointer calls contains() with its parent: + + >>> child = JsonPointer('/foo/bar') + >>> parent = JsonPointer('/foo') + >>> child.contains(parent) + True + >>> parent.contains(child) + False + >>> child.contains(child) + True + >>> child.contains(JsonPointer('')) + True + >>> child.contains(JsonPointer('/foo/b')) + False + """ return self.parts[:len(ptr.parts)] == ptr.parts def __contains__(self, item): - """ Returns True if self contains the given ptr """ + """Equivalent to contains(): item must be a prefix of self. + + >>> JsonPointer('/foo') in JsonPointer('/foo/bar') + True + >>> JsonPointer('/foo/bar') in JsonPointer('/foo') + False + """ return self.contains(item) def join(self, suffix):