Skip to content

Commit bbb14a5

Browse files
Allow string formatting of scalar DataArrays (#5981)
* 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>
1 parent c60f9b0 commit bbb14a5

File tree

2 files changed

+25
-1
lines changed

2 files changed

+25
-1
lines changed

xarray/core/common.py

+4
Original file line numberDiff line numberDiff line change
@@ -158,6 +158,10 @@ def _repr_html_(self):
158158
return f"<pre>{escape(repr(self))}</pre>"
159159
return formatting_html.array_repr(self)
160160

161+
def __format__(self: Any, format_spec: str) -> str:
162+
# we use numpy: scalars will print fine and arrays will raise
163+
return self.values.__format__(format_spec)
164+
161165
def _iter(self: Any) -> Iterator[Any]:
162166
for n in range(len(self)):
163167
yield self[n]

xarray/tests/test_formatting.py

+21-1
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@
99
import xarray as xr
1010
from xarray.core import formatting
1111

12-
from . import requires_netCDF4
12+
from . import requires_dask, requires_netCDF4
1313

1414

1515
class TestFormatting:
@@ -418,6 +418,26 @@ def test_array_repr_variable(self) -> None:
418418
with xr.set_options(display_expand_data=False):
419419
formatting.array_repr(var)
420420

421+
@requires_dask
422+
def test_array_scalar_format(self) -> None:
423+
var = xr.DataArray(0)
424+
assert var.__format__("") == "0"
425+
assert var.__format__("d") == "0"
426+
assert var.__format__(".2f") == "0.00"
427+
428+
var = xr.DataArray([0.1, 0.2])
429+
assert var.__format__("") == "[0.1 0.2]"
430+
with pytest.raises(TypeError) as excinfo:
431+
var.__format__(".2f")
432+
assert "unsupported format string passed to" in str(excinfo.value)
433+
434+
# also check for dask
435+
var = var.chunk(chunks={"dim_0": 1})
436+
assert var.__format__("") == "[0.1 0.2]"
437+
with pytest.raises(TypeError) as excinfo:
438+
var.__format__(".2f")
439+
assert "unsupported format string passed to" in str(excinfo.value)
440+
421441

422442
def test_inline_variable_array_repr_custom_repr() -> None:
423443
class CustomArray:

0 commit comments

Comments
 (0)