experimental Dask array that opens/closes a resource when computing
Low maintenance activity. Last release over 4 years ago, commits in 0 of the last 26 weeks. Weaker on commit activity and recent releases.
pip install resource-backed-dask-arrayresource-backed-dask-array
ResourceBackedDaskArray is an experimental Dask array subclass
that opens/closes a resource when computing (but only once per compute call).
installation
pip install resource-backed-dask-array
motivation for this package
Consider the following class that simulates a file reader capable of returning a dask array (using dask.array.map_blocks) The file handle must be in an open state in order to read a chunk, otherwise it segfaults (or otherwise errors)
import dask.array as da
import numpy as np
class FileReader:
def __init__(self):
self._closed = False
def close(self):
"""close the imaginary file"""
self._closed = True
@property
def closed(self):
return self._closed
def __enter__(self):
if self.closed:
self._closed = False # open
return self
def __exit__(self, *_):
self.close()
def to_dask(self) -> da.Array:
"""Method that returns a dask array for this file."""
return da.map_blocks(
self._dask_block,
chunks=((1,) * 4, 4, 4),
dtype=float,
)
def _dask_block(self):
"""simulate getting a single chunk of the file."""
if self.closed:
raise RuntimeError("Segfault!")
return np.random.rand(1, 4, 4)
As long as the file stays open, everything works fine:
>>> fr = FileReader()
>>> dsk_ary = fr.to_dask()
>>> dsk_ary.compute().shape
(4, 4, 4)