Skip to content

Allow string formatting of scalar DataArrays #5981

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 8 commits into from
May 9, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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