Skip to content

Commit 799200d

Browse files
authored
Allow to_zarr to be a lazy operation by passing compute=False (#884)
1 parent 476af9d commit 799200d

2 files changed

Lines changed: 28 additions & 2 deletions

File tree

cubed/core/ops.py

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -277,7 +277,9 @@ def __iter__(self):
277277
return out
278278

279279

280-
def to_zarr(x: "Array", store, path=None, region=None, executor=None, **kwargs):
280+
def to_zarr(
281+
x: "Array", store, path=None, region=None, compute=True, *, executor=None, **kwargs
282+
):
281283
"""Save an array to Zarr storage.
282284
283285
Note that this operation is eager, and will run the computation
@@ -293,12 +295,17 @@ def to_zarr(x: "Array", store, path=None, region=None, executor=None, **kwargs):
293295
Group path
294296
region : tuple of slices, optional
295297
The region of data that should be written to in target.
298+
compute : boolean, optional
299+
If True compute immediately, return array otherwise.
296300
executor : cubed.runtime.types.Executor, optional
297301
The executor to use to run the computation.
298302
Defaults to using the in-process Python executor.
299303
"""
300304
out = _store_array(x, store, path=path, region=region)
301-
out.compute(executor=executor, _return_in_memory_array=False, **kwargs)
305+
if compute:
306+
out.compute(executor=executor, _return_in_memory_array=False, **kwargs)
307+
else:
308+
return out
302309

303310

304311
def blockwise(

cubed/tests/test_core.py

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -224,6 +224,25 @@ def test_to_zarr_array(tmp_path, spec, executor):
224224
assert_array_equal(res[:], np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]))
225225

226226

227+
def test_to_zarr_lazy_compute(tmp_path, spec):
228+
a = xp.asarray([[1, 2, 3], [4, 5, 6], [7, 8, 9]], chunks=(2, 2), spec=spec)
229+
store = tmp_path / "output.zarr"
230+
z = create_zarr(
231+
np.zeros(a.shape, dtype=a.dtype),
232+
chunks=(2, 2),
233+
store=store,
234+
)
235+
b = cubed.to_zarr(a, z, compute=False)
236+
# target has not been computed yet
237+
res = open_storage_array(store, mode="r")
238+
with pytest.raises(AssertionError):
239+
assert_array_equal(res[:], np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]))
240+
241+
b.compute()
242+
res = open_storage_array(store, mode="r")
243+
assert_array_equal(res[:], np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]))
244+
245+
227246
def test_to_zarr_region(tmp_path, spec, executor):
228247
a = xp.asarray(
229248
[

0 commit comments

Comments
 (0)