Skip to content

Commit 3599f87

Browse files
lukasbindreiterdcherianbenbovy
authored
Update open_dataset backend to ensure compatibility with new explicit index model (#7150)
* Update open_dataset backend to ensure compatibility with new explicit index model * Avoid generation of Indexes object * Add test ensuring backend compatibility with multiindices * Update xarray/tests/test_backends_api.py * Use stack to construct multi index in test * Mention open_dataset backend multi-index compatibility in whats-new * remove _create_multiindex utility function * remove pandas import * Update doc/whats-new.rst Co-authored-by: Deepak Cherian <[email protected]> Co-authored-by: Benoit Bovy <[email protected]> Co-authored-by: Benoit Bovy <[email protected]>
1 parent abc0b5d commit 3599f87

File tree

3 files changed

+22
-1
lines changed

3 files changed

+22
-1
lines changed

doc/whats-new.rst

+2
Original file line numberDiff line numberDiff line change
@@ -70,6 +70,8 @@ Bug fixes
7070
:py:meth:`DataArray.to_index` for multi-index levels (convert to single index).
7171
(:issue:`6836`, :pull:`7105`)
7272
By `Benoît Bovy <https://github.com/benbovy>`_.
73+
- Support for open_dataset backends that return datasets containing multi-indexes (:issue:`7139`, :pull:`7150`)
74+
By `Lukas Bindreiter <https://github.com/lukasbindreiter>`_.
7375

7476
Documentation
7577
~~~~~~~~~~~~~

xarray/backends/api.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -234,7 +234,7 @@ def _get_mtime(filename_or_obj):
234234

235235
def _protect_dataset_variables_inplace(dataset, cache):
236236
for name, variable in dataset.variables.items():
237-
if name not in variable.dims:
237+
if name not in dataset._indexes:
238238
# no need to protect IndexVariable objects
239239
data = indexing.CopyOnWriteArray(variable._data)
240240
if cache:

xarray/tests/test_backends_api.py

+19
Original file line numberDiff line numberDiff line change
@@ -48,6 +48,25 @@ def open_dataset(
4848
assert_identical(expected, actual)
4949

5050

51+
def test_multiindex() -> None:
52+
# GH7139
53+
# Check that we properly handle backends that change index variables
54+
dataset = xr.Dataset(coords={"coord1": ["A", "B"], "coord2": [1, 2]})
55+
dataset = dataset.stack(z=["coord1", "coord2"])
56+
57+
class MultiindexBackend(xr.backends.BackendEntrypoint):
58+
def open_dataset(
59+
self,
60+
filename_or_obj,
61+
drop_variables=None,
62+
**kwargs,
63+
) -> xr.Dataset:
64+
return dataset.copy(deep=True)
65+
66+
loaded = xr.open_dataset("fake_filename", engine=MultiindexBackend)
67+
assert_identical(dataset, loaded)
68+
69+
5170
class PassThroughBackendEntrypoint(xr.backends.BackendEntrypoint):
5271
"""Access an object passed to the `open_dataset` method."""
5372

0 commit comments

Comments
 (0)