diff --git a/lib/iris/cube.py b/lib/iris/cube.py index 4473e494e3..3b9aa1a0e4 100644 --- a/lib/iris/cube.py +++ b/lib/iris/cube.py @@ -1240,6 +1240,16 @@ def __str__(self): def __repr__(self): return "" % self.summary(shorten=True, name_padding=1) + def __iter__(self): + # Emit a warning about iterating over the cube. + # __getitem__ makes this possible, but now deprecated as confusing. + warnings.warn('Cube iteration has been deprecated: ' + 'please use Cube.slices() instead.') + + # Return a simple first-index iterator, equivalent to that produced + # with __getitem__, if __iter__ was not defined. + return (self[i] for i in range(self.shape[0])) + def __getitem__(self, keys): """ Cube indexing (through use of square bracket notation) has been implemented at the data level. That is, diff --git a/lib/iris/tests/test_cdm.py b/lib/iris/tests/test_cdm.py index b3001d3209..8dad778d86 100644 --- a/lib/iris/tests/test_cdm.py +++ b/lib/iris/tests/test_cdm.py @@ -23,6 +23,7 @@ import os import re +import warnings import numpy @@ -503,6 +504,20 @@ def test_ellipsis(self): self.assertCML([self.t[(0, 2), :, Ellipsis]], ('cube_slice', '2d_to_1d_cube_multi_slice3.cml')) +class TestIteration(TestCube2d): + def test_cube_iteration(self): + # Check that creating a cube iterator generates a warning. + with warnings.catch_warnings(): + warnings.simplefilter('error') + with self.assertRaises(UserWarning): + for subcube in self.t: # warning->error, so this *fails* + pass + # Check we can step through the items, and their shape and number. + subcubes = [subcube for subcube in self.t] + self.assertEqual(len(subcubes), self.t.shape[0]) + for subcube in subcubes: + self.assertEqual(subcube.shape, self.t.shape[1:]) + class Test2dSlicing(TestCube2d): def test_cube_slice_all_dimensions(self): for cube in self.t.slices(['dim1', 'dim2']):