Debian Codegraph @

docs/source/how-to/extend-sizeof.rst

raw
1 Extend `sizeof`
2 ===============
3
4 When Dask needs to compute the size of an object in bytes, e.g. to determine which objects to spill to disk, it uses the ``dask.sizeof.sizeof`` registration mechanism. Users who need to define a ``sizeof`` implementation for their own objects can use ``sizeof.register``:
5
6 .. code-block:: python
7
8 >>> import numpy as np
9 >>> from dask.sizeof import sizeof
10 >>> @sizeof.register(np.ndarray)
11 >>> def sizeof_numpy_like(array):
12 ... return array.nbytes
13
14 This code can be executed in order to register the implementation with Dask by placing it in one of the library's modules e.g. ``__init__.py``. However, this introduces a maintenance burden on the developers of these libraries, and must be manually imported on all workers in the event that these libraries do not accept the patch.
15
16 Therefore, Dask also exposes an `entrypoint <https://packaging.python.org/specifications/entry-points/>`_ under the group ``dask.sizeof`` to enable third-party libraries to develop and maintain these ``sizeof`` implementations.
17
18 For a fictitious library ``numpy_sizeof_dask.py``, the necessary ``setup.cfg`` configuration would be as follows:
19
20 .. code-block:: ini
21
22 [options.entry_points]
23 dask.sizeof =
24 numpy = numpy_sizeof_dask:sizeof_plugin
25
26 whilst ``numpy_sizeof_dask.py`` would contain
27
28 .. code-block:: python
29
30 >>> import numpy as np
31 >>> def sizeof_plugin(sizeof):
32 ... @sizeof.register(np.ndarray)
33 ... def sizeof_numpy_like(array):
34 ... return array.nbytes
35
36 Upon the first import of `dask.sizeof`, Dask calls the entrypoint (``sizeof_plugin``) with the ``dask.sizeof.sizeof`` object, which can then be used to register a sizeof implementation.