Skip to content

Commit

Permalink
Merge pull request #135 from OpenDataServices/2023-10-06b
Browse files Browse the repository at this point in the history
Restore jsonschema's type validator, as its performance has improved in recent Python versions
  • Loading branch information
odscjames authored Oct 12, 2023
2 parents 5fe6465 + 639b874 commit b04a6f2
Show file tree
Hide file tree
Showing 2 changed files with 5 additions and 41 deletions.
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,10 @@ and this project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0.
- Dropped support for Python 3.6 & 3.7, as these are now end of life.
- Drop jsonschema 3 support

### Changed

- Restore jsonschema's type validator, as its performance has improved in recent Python versions https://github.com/OpenDataServices/lib-cove/pull/127

## [0.31.0] - 2023-07-06

### Changed
Expand Down
42 changes: 1 addition & 41 deletions libcove/lib/common.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@

from flattentool import unflatten
from jsonschema import FormatChecker, RefResolver
from jsonschema._utils import ensure_list, extras_msg, find_additional_properties, uniq
from jsonschema._utils import extras_msg, find_additional_properties, uniq
from jsonschema.exceptions import UndefinedTypeCheck, ValidationError

from .exceptions import cove_spreadsheet_conversion_error
Expand All @@ -33,43 +33,6 @@
REQUIRED_RE = re.compile(r"^'([^']+)'")


# This function was inlined in jsonschema 4.
def types_msg(instance, types):
"""
Create an error message for a failure to match the given types.
If the ``instance`` is an object and contains a ``name`` property, it will
be considered to be a description of that object and used as its type.
Otherwise the message is simply the reprs of the given ``types``.
"""

reprs = []
for type in types:
try:
reprs.append(repr(type["name"]))
except Exception:
reprs.append(repr(type))
return "%r is not of type %s" % (instance, ", ".join(reprs))


def type_validator(validator, types, instance, schema):
"""
Replace the jsonschema type validator to use for-loop instead of slower
any() with generator expression.
https://github.com/OpenDataServices/lib-cove/pull/66
"""
types = ensure_list(types)

for type in types:
if validator.is_type(instance, type):
break
else:
yield ValidationError(types_msg(instance, types))


class TypeChecker:
def is_type(self, instance, type):
if type == "string":
Expand Down Expand Up @@ -97,9 +60,6 @@ def is_type(self, instance, type):
# Otherwise we could cause conflicts with other software in the same process.
validator = jsonschema.validators.extend(
jsonschema.validators.Draft4Validator,
validators={
"type": type_validator,
},
type_checker=TypeChecker(),
)

Expand Down

0 comments on commit b04a6f2

Please sign in to comment.