xarray-contrib/cf-xarray

"name" custom criteria not working for DataArray

mathause opened this issue · 1 comments

import cf_xarray
import xarray as xr

da = xr.DataArray([1, 2], coords={"lat": [3, 4]})
lat_criteria = {"latitude": {"name": "lat"}}
cf_xarray.set_options(custom_criteria=lat_criteria)
da.cf["latitude"]

Raises

File ~/code/cf-xarray/cf_xarray/accessor.py:223, in _get_custom_criteria(obj, key, criteria)
    219                 results.update((var,))
    220             # also check name specifically since not in attributes
--> 223             elif criterion == "name" and re.match(patterns, var):
    224                 results.update((var,))
    225 return list(results)

File ~/.conda/envs/cf_xarray_dev/lib/python3.11/re/__init__.py:166, in match(pattern, string, flags)
    163 def match(pattern, string, flags=0):
    164     """Try to apply the pattern at the start of the string, returning
    165     a Match object, or None if no match was found."""
--> 166     return _compile(pattern, flags).match(string)

TypeError: expected string or bytes-like object, got 'ReprObject'

because the DataArray is converted to a temporary Dataset which uses a ReprObject as its name. An easy fix is to call str on var here:

elif criterion == "name" and re.match(patterns, var):

It's more tricky if the name of the DataArray corresponds to the custom criteria. Because it is also not possible to use da[name].

import cf_xarray
import xarray as xr

da = xr.DataArray([1, 2], name="lat")

da["lat"] # fails

lat_criteria = {"latitude": {"name": "lat"}}
cf_xarray.set_options(custom_criteria=lat_criteria)
da.cf["latitude"] # fails as well