Skip to content

Commit

Permalink
perf: Use cached lookups for resolving fragments if the referent docu…
Browse files Browse the repository at this point in the history
…ment is known
  • Loading branch information
Stranger6667 committed Dec 16, 2021
1 parent 60242e7 commit 9f86718
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 3 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.rst
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ v4.3.0
* Fix undesired fallback to brute force container uniqueness check on
certain input types (#893)
* Cache reference lookups for subschemas (#893)
* Use cached lookups for resolving fragments if the referent document is known (#893)
* Implement a PEP544 Protocol for validator classes (#890)

v4.2.1
Expand Down
20 changes: 17 additions & 3 deletions jsonschema/validators.py
Original file line number Diff line number Diff line change
Expand Up @@ -757,6 +757,10 @@ def resolving(self, ref):
finally:
self.pop_scope()

@lru_cache()
def _find_in_referrer(self, key):
return list(self._finditem(self.referrer, key))

def _finditem(self, schema, key):
values = deque([schema])
while values:
Expand All @@ -773,8 +777,11 @@ def _find_subschemas(self):

@lru_cache()
def _find_in_subschemas(self, url):
subschemas = self._find_subschemas()
if not subschemas:
return None
uri, fragment = urldefrag(url)
for subschema in self._find_subschemas():
for subschema in subschemas:
target_uri = self._urljoin_cache(
self.resolution_scope, subschema["$id"],
)
Expand Down Expand Up @@ -831,12 +838,19 @@ def resolve_fragment(self, document, fragment):
if not fragment:
return document

if document is self.referrer:
find = self._find_in_referrer
else:

def find(key):
return self._finditem(document, key)

for keyword in ["$anchor", "$dynamicAnchor"]:
for subschema in self._finditem(document, keyword):
for subschema in find(keyword):
if fragment == subschema[keyword]:
return subschema
for keyword in ["id", "$id"]:
for subschema in self._finditem(document, keyword):
for subschema in find(keyword):
if "#" + fragment == subschema[keyword]:
return subschema

Expand Down

0 comments on commit 9f86718

Please sign in to comment.