diff --git a/Changelog.rst b/Changelog.rst index e8678dc686..310e2a5cd9 100644 --- a/Changelog.rst +++ b/Changelog.rst @@ -3,6 +3,8 @@ version 3.17.0 **2024-??-??** +* New keyword parameter to `cf.Field.insert_dimension`: + ``constructs`` (https://github.com/NCAS-CMS/cf-python/issues/719) * Added the ``cell_measures`` and ``coordinates`` keyword arguments to `cf.Field.weights` (https://github.com/NCAS-CMS/cf-python/issues/709) diff --git a/cf/field.py b/cf/field.py index a87ea84afb..cd5dcc3729 100644 --- a/cf/field.py +++ b/cf/field.py @@ -8687,7 +8687,9 @@ def _update_cell_methods( ) # pragma: no cover @_inplace_enabled(default=False) - def insert_dimension(self, axis, position=0, inplace=False): + def insert_dimension( + self, axis, position=0, constructs=False, inplace=False + ): """Insert a size 1 axis into the data array. .. versionadded:: 3.0.0 @@ -8712,6 +8714,13 @@ def insert_dimension(self, axis, position=0, inplace=False): data array. By default the new axis has position 0, the slowest varying position. + constructs: `bool`, optional + If True then also insert the new axis into all + metadata constructs that don't already include it. By + default, metadata constructs are not changed. + + .. versionadded:: 3.17.0 + {{inplace: `bool`, optional}} :Returns: @@ -8755,24 +8764,13 @@ def insert_dimension(self, axis, position=0, inplace=False): : time(1) = [2019-01-01 00:00:00] """ - f = _inplace_enabled_define_and_cleanup(self) - - if axis is None: - axis = f.set_construct(self._DomainAxis(1)) - else: - axis = f.domain_axis( - axis, - key=True, - default=ValueError("Can't identify a unique axis to insert"), - ) - - # Expand the dims in the field construct's data array - super(Field, f).insert_dimension( - axis=axis, position=position, inplace=True + return super().insert_dimension( + axis=axis, + position=position, + constructs=constructs, + inplace=inplace, ) - return f - def indices(self, *mode, **kwargs): """Create indices that define a subspace of the field construct. diff --git a/cf/test/test_Field.py b/cf/test/test_Field.py index 449fd32980..0bdece56c7 100644 --- a/cf/test/test_Field.py +++ b/cf/test/test_Field.py @@ -1143,6 +1143,10 @@ def test_Field_insert_dimension(self): self.assertEqual(g.ndim, f.ndim + 1) self.assertEqual(g.get_data_axes()[1:], f.get_data_axes()) + self.assertEqual(g.cell_measure().ndim, 2) + h = g.insert_dimension(None, constructs=True) + self.assertEqual(h.cell_measure().ndim, 3) + with self.assertRaises(ValueError): f.insert_dimension(1, "qwerty")