Skip to content

Commit

Permalink
Don't access data when creating DataArray from Variable. (pydata#8754)
Browse files Browse the repository at this point in the history
* Don't access data when creating DataArray from Variable.

Closes pydata#8573

* Fix DataArray

* Fix test

* Add comment
  • Loading branch information
dcherian authored Apr 4, 2024
1 parent 40b3f2c commit 56182f7
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 4 deletions.
9 changes: 7 additions & 2 deletions xarray/core/variable.py
Original file line number Diff line number Diff line change
Expand Up @@ -264,8 +264,13 @@ def as_compatible_data(

from xarray.core.dataarray import DataArray

if isinstance(data, (Variable, DataArray)):
return data.data
# TODO: do this uwrapping in the Variable/NamedArray constructor instead.
if isinstance(data, Variable):
return cast("T_DuckArray", data._data)

# TODO: do this uwrapping in the DataArray constructor instead.
if isinstance(data, DataArray):
return cast("T_DuckArray", data._variable._data)

if isinstance(data, NON_NUMPY_SUPPORTED_ARRAY_TYPES):
data = _possibly_convert_datetime_or_timedelta_index(data)
Expand Down
14 changes: 12 additions & 2 deletions xarray/tests/test_dataarray.py
Original file line number Diff line number Diff line change
Expand Up @@ -4947,7 +4947,7 @@ def test_idxmin(
with pytest.raises(ValueError):
xr.DataArray(5).idxmin()

coordarr0 = xr.DataArray(ar0.coords["x"], dims=["x"])
coordarr0 = xr.DataArray(ar0.coords["x"].data, dims=["x"])
coordarr1 = coordarr0.copy()

hasna = np.isnan(minindex)
Expand Down Expand Up @@ -5062,7 +5062,7 @@ def test_idxmax(
with pytest.raises(ValueError):
xr.DataArray(5).idxmax()

coordarr0 = xr.DataArray(ar0.coords["x"], dims=["x"])
coordarr0 = xr.DataArray(ar0.coords["x"].data, dims=["x"])
coordarr1 = coordarr0.copy()

hasna = np.isnan(maxindex)
Expand Down Expand Up @@ -7167,3 +7167,13 @@ def test_nD_coord_dataarray() -> None:
_assert_internal_invariants(da4, check_default_indexes=True)
assert "x" not in da4.xindexes
assert "x" in da4.coords


def test_lazy_data_variable_not_loaded():
# GH8753
array = InaccessibleArray(np.array([1, 2, 3]))
v = Variable(data=array, dims="x")
# No data needs to be accessed, so no error should be raised
da = xr.DataArray(v)
# No data needs to be accessed, so no error should be raised
xr.DataArray(da)

0 comments on commit 56182f7

Please sign in to comment.