Skip to content

Commit

Permalink
Allow string formatting of scalar DataArrays (#5981)
Browse files Browse the repository at this point in the history
* Allow string formatting of scalar DataArrays

* better comments

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* forgot type check

* yeah, typing is new to me

* Simpler: pass to numpy in all cases

* Add dask test

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
  • Loading branch information
fmaussion and pre-commit-ci[bot] authored May 9, 2022
1 parent c60f9b0 commit bbb14a5
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 1 deletion.
4 changes: 4 additions & 0 deletions xarray/core/common.py
Original file line number Diff line number Diff line change
Expand Up @@ -158,6 +158,10 @@ def _repr_html_(self):
return f"<pre>{escape(repr(self))}</pre>"
return formatting_html.array_repr(self)

def __format__(self: Any, format_spec: str) -> str:
# we use numpy: scalars will print fine and arrays will raise
return self.values.__format__(format_spec)

def _iter(self: Any) -> Iterator[Any]:
for n in range(len(self)):
yield self[n]
Expand Down
22 changes: 21 additions & 1 deletion xarray/tests/test_formatting.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
import xarray as xr
from xarray.core import formatting

from . import requires_netCDF4
from . import requires_dask, requires_netCDF4


class TestFormatting:
Expand Down Expand Up @@ -418,6 +418,26 @@ def test_array_repr_variable(self) -> None:
with xr.set_options(display_expand_data=False):
formatting.array_repr(var)

@requires_dask
def test_array_scalar_format(self) -> None:
var = xr.DataArray(0)
assert var.__format__("") == "0"
assert var.__format__("d") == "0"
assert var.__format__(".2f") == "0.00"

var = xr.DataArray([0.1, 0.2])
assert var.__format__("") == "[0.1 0.2]"
with pytest.raises(TypeError) as excinfo:
var.__format__(".2f")
assert "unsupported format string passed to" in str(excinfo.value)

# also check for dask
var = var.chunk(chunks={"dim_0": 1})
assert var.__format__("") == "[0.1 0.2]"
with pytest.raises(TypeError) as excinfo:
var.__format__(".2f")
assert "unsupported format string passed to" in str(excinfo.value)


def test_inline_variable_array_repr_custom_repr() -> None:
class CustomArray:
Expand Down

0 comments on commit bbb14a5

Please sign in to comment.