Skip to content

Commit e00e51f

Browse files
ColemanTommathausedcherian
authored
Ensure encoding["source"] is available for a pathlib.Path object (#6974)
* Ensure 'source' is encoded even when its a Path Resolves Issue #5888. With this change, the "source" encoding will be stored whether the filename is a string or a Path object. * Add a test for encoding source with Path object * Update whats-new.rst * Ensure only string and Path filenames encode source Co-authored-by: Mathias Hauser <[email protected]> * Update doc/whats-new.rst * fix link Co-authored-by: Mathias Hauser <[email protected]> Co-authored-by: Deepak Cherian <[email protected]>
1 parent 073f414 commit e00e51f

File tree

3 files changed

+16
-3
lines changed

3 files changed

+16
-3
lines changed

doc/whats-new.rst

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -65,6 +65,8 @@ Bug fixes
6565
By `András Gunyhó <https://github.com/mgunyho>`_.
6666
- Avoid use of random numbers in `test_weighted.test_weighted_operations_nonequal_coords` (:issue:`6504`, :pull:`6961`).
6767
By `Luke Conibear <https://github.com/lukeconibear>`_.
68+
- ``Dataset.encoding['source']`` now exists when reading from a Path object (:issue:`5888`, :pull:`6974`)
69+
By `Thomas Coleman <https://github.com/ColemanTom>`_.
6870

6971
Documentation
7072
~~~~~~~~~~~~~

xarray/backends/api.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -358,9 +358,9 @@ def _dataset_from_backend_dataset(
358358

359359
ds.set_close(backend_ds._close)
360360

361-
# Ensure source filename always stored in dataset object (GH issue #2550)
362-
if "source" not in ds.encoding and isinstance(filename_or_obj, str):
363-
ds.encoding["source"] = filename_or_obj
361+
# Ensure source filename always stored in dataset object
362+
if "source" not in ds.encoding and isinstance(filename_or_obj, (str, os.PathLike)):
363+
ds.encoding["source"] = _normalize_path(filename_or_obj)
364364

365365
return ds
366366

xarray/tests/test_backends.py

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5068,6 +5068,17 @@ def test_source_encoding_always_present() -> None:
50685068
assert ds.encoding["source"] == tmp
50695069

50705070

5071+
@requires_scipy_or_netCDF4
5072+
def test_source_encoding_always_present_with_pathlib() -> None:
5073+
# Test for GH issue #5888.
5074+
rnddata = np.random.randn(10)
5075+
original = Dataset({"foo": ("x", rnddata)})
5076+
with create_tmp_file() as tmp:
5077+
original.to_netcdf(tmp)
5078+
with open_dataset(Path(tmp)) as ds:
5079+
assert ds.encoding["source"] == tmp
5080+
5081+
50715082
def _assert_no_dates_out_of_range_warning(record):
50725083
undesired_message = "dates out of range"
50735084
for warning in record:

0 commit comments

Comments
 (0)