From 933c045f54a9987ca6a6c43f22e6a1e33fe842d9 Mon Sep 17 00:00:00 2001 From: dangotbanned <125183946+dangotbanned@users.noreply.github.com> Date: Sun, 25 Aug 2024 13:51:32 +0100 Subject: [PATCH] perf: Avoid expensive exceptions in `_FromDict.from_dict` 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. --- tools/schemapi/schemapi.py | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/tools/schemapi/schemapi.py b/tools/schemapi/schemapi.py index b3fac3318..fd1164fe3 100644 --- a/tools/schemapi/schemapi.py +++ b/tools/schemapi/schemapi.py @@ -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):