-
-
Notifications
You must be signed in to change notification settings - Fork 407
refactor/consolidated JSON IO routines #3998
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
d-v-b
wants to merge
11
commits into
zarr-developers:main
Choose a base branch
from
d-v-b:refactor/json-io
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
11 commits
Select commit
Hold shift + click to select a range
76e20a0
feat: add free functions for JSON document I/O
d-v-b 7a4b012
refactor: route JSON document I/O through the free functions
d-v-b 2b88e42
refactor: remove the unused private JSON/bytes store methods
d-v-b 59a7d74
doc: add changelog fragment for the JSON I/O refactor
d-v-b 4c5e722
refactor: make json_to_buffer pure (no config read)
d-v-b 4672cb4
doc: rename changelog fragment to PR number 3998
d-v-b c43fa7a
test: cover the malformed-metadata branches in contains_array/group
d-v-b 60650f2
Update src/zarr/core/_json.py
d-v-b 7affadb
Merge branch 'main' into refactor/json-io
d-v-b d219dd4
fix: missing import
d-v-b 72235a3
doc: address review nits on _json.py docstrings
d-v-b File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1 @@ | ||
| Centralized JSON document I/O behind free functions in `zarr.core._json` and removed the unused private `Store._get_bytes`/`_get_json` methods and their per-store overrides. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,133 @@ | ||
| """Helpers for moving JSON documents in and out of zarr stores. | ||
|
|
||
| These are free functions, deliberately not methods on the ``Store`` ABC: | ||
| reading and writing JSON is a composition of the store's ``get``/``set`` | ||
| primitives with a buffer/JSON conversion, not part of the store contract. | ||
| Keeping them as functions means stores cannot (and need not) override them, | ||
| and the ``Store`` definition stays free of any dependency on the buffer | ||
| prototype. | ||
|
|
||
| These functions are pure: the JSON encoding parameters (``indent``, | ||
| ``allow_nan``) are explicit arguments rather than read from the global config. | ||
| Callers that want zarr's configured indentation pass | ||
| ``indent=config.get("json_indent")``. | ||
|
|
||
| Two layers: | ||
|
|
||
| - ``buffer_to_json`` / ``json_to_buffer`` convert between a ``Buffer`` and a | ||
| parsed JSON value. The buffer prototype lives here, at buffer construction, | ||
| where it is meaningful. | ||
| - ``get_json`` / ``set_json`` compose those with ``Store.get`` / ``Store.set``. | ||
| ``get_json`` returns ``None`` for a missing key (the contract most callers | ||
| want); callers that require presence check for ``None`` themselves. | ||
| """ | ||
|
|
||
| from __future__ import annotations | ||
|
|
||
| import json | ||
| from typing import TYPE_CHECKING, cast | ||
|
|
||
| from zarr.core.buffer import default_buffer_prototype | ||
|
|
||
| if TYPE_CHECKING: | ||
| from zarr.abc.store import ByteRequest, Store | ||
| from zarr.core.buffer import Buffer, BufferPrototype | ||
| from zarr.core.common import JSON | ||
|
|
||
|
|
||
| def buffer_to_json(buffer: Buffer) -> JSON: | ||
| """Parse the contents of a `Buffer` as a JSON value.""" | ||
| # json.loads is typed as returning Any; the result is by definition JSON. | ||
| return cast("JSON", json.loads(buffer.to_bytes())) | ||
|
|
||
|
|
||
| def buffer_to_json_object(buffer: Buffer) -> dict[str, JSON]: | ||
| """Parse the contents of a `Buffer` as a JSON object (a `dict`). | ||
|
|
||
| Every metadata document zarr reads is a JSON object, so this narrows the | ||
| `JSON` union to `dict[str, JSON]` once, here, instead of at each call site. | ||
|
|
||
| Parameters | ||
| ---------- | ||
| buffer | ||
| The buffer whose contents are parsed as a JSON object. | ||
|
|
||
| Raises | ||
| ------ | ||
| TypeError | ||
| If the parsed value is not a JSON object. | ||
| """ | ||
| obj = buffer_to_json(buffer) | ||
| if not isinstance(obj, dict): | ||
| raise TypeError(f"Expected a JSON object, got {type(obj).__name__}.") | ||
| return obj | ||
|
|
||
|
|
||
| def json_to_buffer( | ||
| obj: JSON, | ||
| *, | ||
| prototype: BufferPrototype | None = None, | ||
| indent: int | None = None, | ||
| allow_nan: bool = True, | ||
| ) -> Buffer: | ||
| """Serialize a JSON value into a `Buffer`. | ||
|
|
||
| Parameters | ||
| ---------- | ||
| obj | ||
| The JSON-serializable value to encode. | ||
| prototype | ||
| The buffer prototype to construct the result with. Defaults to | ||
| `default_buffer_prototype()`. | ||
| indent | ||
| Indentation passed to `json.dumps`. `None` (the default) writes | ||
| without newline indentation, using json's default separators. | ||
| Callers that want zarr's configured indentation pass | ||
| `indent=config.get("json_indent")`. | ||
| allow_nan | ||
| Whether to permit `NaN`/`Infinity` in the output, passed to | ||
| `json.dumps`. | ||
| """ | ||
| if prototype is None: | ||
| prototype = default_buffer_prototype() | ||
| return prototype.buffer.from_bytes(json.dumps(obj, indent=indent, allow_nan=allow_nan).encode()) | ||
|
|
||
|
|
||
| async def get_json(store: Store, key: str, *, byte_range: ByteRequest | None = None) -> JSON | None: | ||
| """Read and parse the JSON document at `key`, or `None` if it is absent. | ||
|
|
||
| Parameters | ||
| ---------- | ||
| store | ||
| The store to read from. | ||
| key | ||
| The key identifying the JSON document. | ||
| byte_range | ||
| If given, read only this portion of the value. Note that a partial | ||
| read of a JSON document may not be valid JSON. | ||
|
|
||
| Returns | ||
| ------- | ||
| JSON or None | ||
| The parsed JSON value, or `None` if `key` does not exist. | ||
| """ | ||
| buffer = await store.get(key, default_buffer_prototype(), byte_range) | ||
| return None if buffer is None else buffer_to_json(buffer) | ||
|
|
||
|
|
||
| async def set_json( | ||
| store: Store, | ||
| key: str, | ||
| obj: JSON, | ||
| *, | ||
| prototype: BufferPrototype | None = None, | ||
| indent: int | None = None, | ||
| allow_nan: bool = True, | ||
| ) -> None: | ||
| """Serialize `obj` as JSON and write it to `key` in `store`. | ||
|
|
||
| `indent` and `allow_nan` are forwarded to `json_to_buffer`. | ||
| """ | ||
| await store.set( | ||
| key, json_to_buffer(obj, prototype=prototype, indent=indent, allow_nan=allow_nan) | ||
| ) | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Seems trivial, but do you want to add a Parameters section?