From 5967991485014f4ca4d4133860e5a1451cb3e45a Mon Sep 17 00:00:00 2001 From: David Hassell Date: Thu, 30 May 2024 12:07:13 +0100 Subject: [PATCH] cf.field.cell_methods bug fix --- Changelog.rst | 11 +++++++++++ cfdm/field.py | 19 +++++++++++++++++++ cfdm/test/test_Field.py | 4 ++++ 3 files changed, 34 insertions(+) diff --git a/Changelog.rst b/Changelog.rst index 301219bae..7636bb5ae 100644 --- a/Changelog.rst +++ b/Changelog.rst @@ -1,3 +1,14 @@ +Version NEXTVERSION +------------------- + +**2024-??-??** + +* Fix bug that returned incorrect results when an invalid identifer is + provided to `cf.Field.cell_methods` + (https://github.com/NCAS-CMS/cfdm/issues/2699) + +---- + Version 1.11.1.0 ---------------- diff --git a/cfdm/field.py b/cfdm/field.py index 90ba5a5f3..61b1d1f1d 100644 --- a/cfdm/field.py +++ b/cfdm/field.py @@ -662,6 +662,18 @@ def cell_methods(self, *identities, **filter_kwargs): **Examples** + >>> f = {{package}}.example_field(1) + >>> print(f.cell_methods()) + Constructs: + {'cellmethod0': , + 'cellmethod1': } + >>> print(f.cell_methods('time')) + Constructs: + {'cellmethod1': } + >>> print(f.cell_methods('bad identifier')) + Constructs: + {} + """ cached = filter_kwargs.get("cached") if cached is not None: @@ -702,6 +714,13 @@ def cell_methods(self, *identities, **filter_kwargs): keys.add(cm_key) identities = () + if not keys: + # Specify a key of None to ensure that no cell methods + # are selected. (If keys is an empty set then all cell + # methods are selected, which is not what we want, + # here.) + keys = (None,) + filter_kwargs = { "filter_by_key": keys, "todict": filter_kwargs.pop("todict", False), diff --git a/cfdm/test/test_Field.py b/cfdm/test/test_Field.py index cc6ab7b22..a5a33e905 100644 --- a/cfdm/test/test_Field.py +++ b/cfdm/test/test_Field.py @@ -355,6 +355,10 @@ def test_Field_CONSTRUCTS(self): for key, value in constructs.items(): self.assertIsInstance(value, cfdm.CellMethod) + # Check that no cell methods are returned when a bad + # identifier is provided + self.assertFalse(f.cell_methods("bad identifier")) + constructs = f.coordinate_references() n = 2 self.assertEqual(len(constructs), n)