@@ -104,9 +104,11 @@ def _open_dataset(
104104 # How should we handle concat_dim, and other xr.open_mfdataset kwargs?
105105 xarray_open_kwargs .update (preprocess = preprocess )
106106 xarray_open_kwargs .update (parallel = True )
107- ds = xr .open_mfdataset (url , ** xarray_open_kwargs )
107+ # ds = xr.open_mfdataset(url, **xarray_open_kwargs)
108+ ds = _open_dataset_try_auto (url , xr .open_mfdataset , xarray_open_kwargs )
108109 else :
109- ds = xr .open_dataset (url , ** xarray_open_kwargs )
110+ # ds = xr.open_dataset(url, **xarray_open_kwargs)
111+ ds = _open_dataset_try_auto (url , xr .open_dataset , xarray_open_kwargs )
110112 if preprocess is not None :
111113 ds = preprocess (ds )
112114
@@ -137,6 +139,30 @@ def _open_dataset(
137139 return ds
138140
139141
142+ def _open_dataset_try_auto (url , func : typing .Callable , xarray_open_kwargs ) -> xr .Dataset :
143+ """
144+ Try to open a dataset with chunks set to auto. If we fail because dask doesn't know how to chunk
145+ it, set chunks to `{}` and retry. Handles cases where datasets contain things like string variables,
146+ which can't be autochunked, as that's restricted to cftime arrays only.
147+
148+ Attempting to autochunk, rather than always using disk chunks (`{}`) is advantageous as it is generally
149+ quite a lot more performant. Unfortunately, there is no straightforward way to detect which variables
150+ within a dataset can and can't be autochunked without opening it.
151+ """
152+ try :
153+ ds = func (url , ** xarray_open_kwargs )
154+ except NotImplementedError as exc :
155+ if (
156+ 'Can not use auto rechunking with object dtype. We are unable to estimate the size in bytes of object data'
157+ in str (exc )
158+ ):
159+ xarray_open_kwargs ['chunks' ] = {}
160+ ds = func (url , ** xarray_open_kwargs )
161+ else :
162+ raise exc
163+ return ds
164+
165+
140166def _update_attrs (* , additional_attrs , ds ):
141167 additional_attrs = additional_attrs or {}
142168 if additional_attrs :
0 commit comments