Skip to content

Commit be4b4a5

Browse files
authored
Fix bug where unmapped keys were discarded. (#56)
Fix apply_mapper to set defaults when receiving an empty list from mapper functions. This got removed in an earlier cleanup commit by mistake.
1 parent 000c7f3 commit be4b4a5

File tree

2 files changed

+34
-4
lines changed

2 files changed

+34
-4
lines changed

cf_xarray/accessor.py

Lines changed: 25 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -124,17 +124,37 @@ def apply_mapper(
124124
) -> List[Any]:
125125
"""
126126
Applies a mapping function; does error handling / returning defaults.
127+
128+
Expects the mapper function to raise an error if passed a bad key.
129+
It should return a list in all other cases including when there are no
130+
results for a good key.
127131
"""
132+
133+
def _maybe_return_default():
134+
"""
135+
Used when mapper raises an error or returns empty list.
136+
Sets a default if possible else sets []
137+
"""
138+
if error:
139+
raise KeyError(
140+
f"cf-xarray cannot interpret key {key!r}. Perhaps some needed attributes are missing."
141+
)
142+
if default:
143+
results = [default]
144+
else:
145+
results = []
146+
return results
147+
128148
try:
129149
results = mapper(obj, key)
130150
except Exception as e:
131151
if error:
132152
raise e
133153
else:
134-
if default:
135-
results = [default] # type: ignore
136-
else:
137-
results = []
154+
results = _maybe_return_default()
155+
156+
if not results:
157+
results = _maybe_return_default()
138158

139159
return results
140160

@@ -204,6 +224,7 @@ def _get_axis_coord(var: Union[DataArray, Dataset], key: str,) -> List[str]:
204224
expected = valid_values[key]
205225
if var.coords[coord].attrs.get(criterion, None) in expected:
206226
results.update((coord,))
227+
207228
return list(results)
208229

209230

cf_xarray/tests/test_accessor.py

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -183,6 +183,15 @@ def test_kwargs_methods(obj):
183183
assert_identical(expected, actual)
184184

185185

186+
def test_preserve_unused_keys():
187+
188+
ds = airds.copy(deep=True)
189+
ds.time.attrs.clear()
190+
actual = ds.cf.sel(X=260, Y=40, time=airds.time[:2], method="nearest")
191+
expected = ds.sel(lon=260, lat=40, time=airds.time[:2], method="nearest")
192+
assert_identical(actual, expected)
193+
194+
186195
def test_kwargs_expand_key_to_multiple_keys():
187196

188197
actual = multiple.cf.isel(X=5, Y=3)

0 commit comments

Comments
 (0)