Skip to content

Commit

Permalink
perf: Avoid expensive exceptions in _FromDict.from_dict
Browse files Browse the repository at this point in the history
Try running `hatch test --all` on main vs this.
Locally, each version gets a 1.32-1.53x speedup.
Somehow this also includes `3.11`, despite that being the version "zero-cost" exceptions were introduced.
  • Loading branch information
dangotbanned committed Aug 25, 2024
1 parent 8ca4266 commit 933c045
Showing 1 changed file with 6 additions and 5 deletions.
11 changes: 6 additions & 5 deletions tools/schemapi/schemapi.py
Original file line number Diff line number Diff line change
Expand Up @@ -1568,11 +1568,12 @@ def from_dict(
if "anyOf" in resolved or "oneOf" in resolved:
schemas = resolved.get("anyOf", []) + resolved.get("oneOf", [])
for possible in schemas:
try:
validate_jsonschema_fail_fast(dct, possible, rootschema=root_schema)
except ValidationError:
continue
else:
# NOTE: Instead of raise/except/continue
# Pre-"zero-cost" exceptions, this has a huge performance gain.
# https://docs.python.org/3/whatsnew/3.11.html#misc
# https://github.com/python/cpython/blob/9b3749849eda4012261a112b22eb07f26fd345a9/InternalDocs/exception_handling.md
it_errs = _validator(possible, root_schema).iter_errors(dct)
if next(it_errs, None) is None:
return from_dict(dct, schema=possible, default_class=target_tp)

if _is_dict(dct):
Expand Down

0 comments on commit 933c045

Please sign in to comment.