diff --git a/xarray/core/common.py b/xarray/core/common.py index 3db9b1cfa0c..cf02bcff77b 100644 --- a/xarray/core/common.py +++ b/xarray/core/common.py @@ -158,6 +158,10 @@ def _repr_html_(self): return f"
{escape(repr(self))}" 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] diff --git a/xarray/tests/test_formatting.py b/xarray/tests/test_formatting.py index 4bbf41c7b38..a5c044d8ea7 100644 --- a/xarray/tests/test_formatting.py +++ b/xarray/tests/test_formatting.py @@ -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: @@ -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: