Skip to content

Commit 11ea76d

Browse files
committed
Warn when a variable referred to in an attribute was not found
1 parent 3c1ca8f commit 11ea76d

File tree

2 files changed

+14
-1
lines changed

2 files changed

+14
-1
lines changed

cf_xarray/accessor.py

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
import inspect
33
import itertools
44
import textwrap
5+
import warnings
56
from collections import ChainMap
67
from contextlib import suppress
78
from typing import (
@@ -776,8 +777,17 @@ def __getitem__(self, key: Union[str, List[str]]):
776777

777778
if scalar_key and len(varnames) == 1:
778779
da = ds[varnames[0]]
780+
failed = []
779781
for k1 in coords:
780-
da.coords[k1] = ds.variables[k1]
782+
if k1 not in ds.variables:
783+
failed.append(k1)
784+
else:
785+
da.coords[k1] = ds.variables[k1]
786+
if failed:
787+
warnings.warn(
788+
f"Variables {failed!r} not found in object but are referred to in the CF attributes.",
789+
UserWarning,
790+
)
781791
return da
782792

783793
ds = ds.reset_coords()[varnames + coords]

cf_xarray/tests/test_accessor.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -83,6 +83,9 @@ def test_getitem_ancillary_variables():
8383
assert_identical(anc.cf["q"], expected)
8484
assert_identical(anc.cf["specific_humidity"], expected)
8585

86+
with pytest.warns(UserWarning):
87+
anc[["q"]].cf["q"]
88+
8689

8790
@pytest.mark.parametrize("obj", objects)
8891
@pytest.mark.parametrize(

0 commit comments

Comments
 (0)