Skip to content

Commit

Permalink
refactor: Reuse JSONEncoder for hashing
Browse files Browse the repository at this point in the history
  • Loading branch information
dangotbanned committed Aug 30, 2024
1 parent 96dde18 commit ab20005
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 4 deletions.
6 changes: 4 additions & 2 deletions altair/utils/schemapi.py
Original file line number Diff line number Diff line change
Expand Up @@ -259,6 +259,8 @@ def _validator_for(uri: str, /) -> Callable[..., Validator]:
return tp


_HASH_ENCODER = json.JSONEncoder(sort_keys=True, separators=(",", ":"))

if Version(importlib_version("jsonschema")) >= Version("4.18"):
from referencing import Registry
from referencing.jsonschema import specification_with as _specification_with
Expand Down Expand Up @@ -381,7 +383,7 @@ def _registry_comp_key(root: Map, dialect_id: str, /) -> tuple[str, str]:
elif len(root) == 1:
k1 = "".join(f"{s!s}" for s in chain(*root.items()))
else:
k1 = json.dumps(root, separators=(",", ":"), sort_keys=True)
k1 = _HASH_ENCODER.encode(root)
return k1, dialect_id

def resolve_references_rpds(schema: Map, rootschema: Map) -> HashTrieMap[str, Any]:
Expand Down Expand Up @@ -1539,7 +1541,7 @@ def _hash_schema(
"""
if isinstance(schema, Mapping):
schema = {k: v for k, v in schema.items() if k not in exclude}
return hash(json.dumps(schema, sort_keys=True))
return hash(_HASH_ENCODER.encode(schema))


def _subclasses(cls: type[TSchemaBase]) -> Iterator[type[TSchemaBase]]:
Expand Down
6 changes: 4 additions & 2 deletions tools/schemapi/schemapi.py
Original file line number Diff line number Diff line change
Expand Up @@ -257,6 +257,8 @@ def _validator_for(uri: str, /) -> Callable[..., Validator]:
return tp


_HASH_ENCODER = json.JSONEncoder(sort_keys=True, separators=(",", ":"))

if Version(importlib_version("jsonschema")) >= Version("4.18"):
from referencing import Registry
from referencing.jsonschema import specification_with as _specification_with
Expand Down Expand Up @@ -379,7 +381,7 @@ def _registry_comp_key(root: Map, dialect_id: str, /) -> tuple[str, str]:
elif len(root) == 1:
k1 = "".join(f"{s!s}" for s in chain(*root.items()))
else:
k1 = json.dumps(root, separators=(",", ":"), sort_keys=True)
k1 = _HASH_ENCODER.encode(root)
return k1, dialect_id

def resolve_references_rpds(schema: Map, rootschema: Map) -> HashTrieMap[str, Any]:
Expand Down Expand Up @@ -1537,7 +1539,7 @@ def _hash_schema(
"""
if isinstance(schema, Mapping):
schema = {k: v for k, v in schema.items() if k not in exclude}
return hash(json.dumps(schema, sort_keys=True))
return hash(_HASH_ENCODER.encode(schema))


def _subclasses(cls: type[TSchemaBase]) -> Iterator[type[TSchemaBase]]:
Expand Down

0 comments on commit ab20005

Please sign in to comment.