diff --git a/changelog/7122.bugfix.rst b/changelog/7122.bugfix.rst new file mode 100644 index 0000000000..2202bd73c2 --- /dev/null +++ b/changelog/7122.bugfix.rst @@ -0,0 +1,3 @@ +:user:`gaoflow` fixed coordinate summaries so that length-0 string and +date-like coordinates print as empty arrays instead of raising +``ValueError``. (:issue:`6531`) diff --git a/lib/iris/coords.py b/lib/iris/coords.py index da712d6e2a..5f35fc0a5f 100644 --- a/lib/iris/coords.py +++ b/lib/iris/coords.py @@ -406,8 +406,9 @@ def array_summary(data, n_max, n_edge, linewidth, precision): if data.dtype.kind == "U": # Strings : N.B. includes all missing data - # find the longest. - length = max(len(str(x)) for x in data.flatten()) + # find the longest (an empty array, e.g. a length-0 time + # coordinate, has no elements, so fall back to 0). See #6531. + length = max((len(str(x)) for x in data.flatten()), default=0) # Pre-apply a common formatting width. formatter = {"all": lambda x: str(x).ljust(length)} diff --git a/lib/iris/tests/unit/coords/test_Coord.py b/lib/iris/tests/unit/coords/test_Coord.py index 697a6f86d4..28d0689288 100644 --- a/lib/iris/tests/unit/coords/test_Coord.py +++ b/lib/iris/tests/unit/coords/test_Coord.py @@ -1482,6 +1482,37 @@ def test_long_time_interval__bounded(self): result = coord.__str__() assert expected == result + def test_empty_time_coord(self): + # A length-0 time coordinate (an as-yet-unfilled unlimited dimension) + # should print rather than raising (#6531). + coord = DimCoord([], standard_name="time", units="days since 1970-01-01") + expected = "\n".join( + [ + "DimCoord : time / (days since 1970-01-01, standard calendar)", + " points: []", + " shape: (0,)", + " dtype: float64", + " standard_name: 'time'", + ] + ) + result = coord.__str__() + assert expected == result + + def test_empty_string_coord(self): + # A length-0 string coordinate also exercises the empty-array path. + coord = AuxCoord(np.array([], dtype="