Skip to content

Commit

Permalink
Document the behaviour of converting a Dask array to a Python number
Browse files Browse the repository at this point in the history
  • Loading branch information
bouweandela committed Dec 18, 2023
1 parent 6f21008 commit d638f45
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 0 deletions.
15 changes: 15 additions & 0 deletions dask/array/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -1858,6 +1858,9 @@ def to_backend(self, backend: str | None = None, **kwargs):
return to_backend(self, backend=backend, **kwargs)

def __bool__(self):
"""Compute the value of a length-1 array and convert it to
:class:`bool`.
"""
if self.size > 1:
raise ValueError(
f"The truth value of a {self.__class__.__name__} is ambiguous. "
Expand All @@ -1875,17 +1878,29 @@ def _scalarfunc(self, cast_type):
return cast_type(self.compute().item())

def __int__(self):
"""Compute the value of a length-1 array and convert it to
:class:`int`.
"""
return self._scalarfunc(int)

__long__ = __int__ # python 2

def __float__(self):
"""Compute the value of a length-1 array and convert it to
:class:`float`.
"""
return self._scalarfunc(float)

def __complex__(self):
"""Compute the value of a length-1 array and convert it to
:class:`complex`.
"""
return self._scalarfunc(complex)

def __index__(self):
"""Compute the value of a length-1 array and pass it to
:func:`operator.index`.
"""
return self._scalarfunc(operator.index)

def __setitem__(self, key, value):
Expand Down
5 changes: 5 additions & 0 deletions docs/source/array-api.rst
Original file line number Diff line number Diff line change
Expand Up @@ -320,6 +320,11 @@ Array
Array.view
Array.vindex
Array.visualize
Array.__bool__
Array.__complex__
Array.__float__
Array.__index__
Array.__int__


Fast Fourier Transforms
Expand Down

0 comments on commit d638f45

Please sign in to comment.