Skip to content

Commit 0d183c5

Browse files
committed
Ensures open_mfdataset attributes are retained
Uses attributes from first file opened by `open_mfdataset` to populate ds.attrs.
1 parent 65555b8 commit 0d183c5

File tree

2 files changed

+23
-1
lines changed

2 files changed

+23
-1
lines changed

xarray/backends/api.py

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -437,7 +437,8 @@ def open_mfdataset(paths, chunks=None, concat_dim=_CONCAT_DIM_DEFAULT,
437437
lock=None, **kwargs):
438438
"""Open multiple files as a single dataset.
439439
440-
Experimental. Requires dask to be installed.
440+
Requires dask to be installed. Attributes from the first dataset file
441+
are used for the combined dataset.
441442
442443
Parameters
443444
----------
@@ -515,6 +516,8 @@ def open_mfdataset(paths, chunks=None, concat_dim=_CONCAT_DIM_DEFAULT,
515516
else:
516517
combined = auto_combine(datasets, concat_dim=concat_dim, compat=compat)
517518
combined._file_obj = _MultiFileCloser(file_objs)
519+
combined.attrs = datasets[0].attrs
520+
518521
return combined
519522

520523

xarray/tests/test_backends.py

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1057,6 +1057,25 @@ def test_open_mfdataset(self):
10571057
with self.assertRaisesRegexp(IOError, 'no files to open'):
10581058
open_mfdataset('foo-bar-baz-*.nc')
10591059

1060+
def test_attrs_mfdataset(self):
1061+
original = Dataset({'foo': ('x', np.random.randn(10))})
1062+
with create_tmp_file() as tmp1:
1063+
with create_tmp_file() as tmp2:
1064+
ds1 = original.isel(x=slice(5))
1065+
ds2 = original.isel(x=slice(5, 10))
1066+
ds1.attrs['test1'] = 'foo'
1067+
ds2.attrs['test2'] = 'bar'
1068+
ds1.to_netcdf(tmp1)
1069+
ds2.to_netcdf(tmp2)
1070+
with open_mfdataset([tmp1, tmp2]) as actual:
1071+
# presumes that attributes inherited from
1072+
# first dataset loaded
1073+
self.assertEqual(actual.test1, ds1.test1)
1074+
# attributes from ds2 are not retained, e.g.,
1075+
with self.assertRaisesRegexp(AttributeError,
1076+
'no attribute'):
1077+
actual.test2
1078+
10601079
def test_preprocess_mfdataset(self):
10611080
original = Dataset({'foo': ('x', np.random.randn(10))})
10621081
with create_tmp_file() as tmp:

0 commit comments

Comments
 (0)