Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Don't access data when creating DataArray from Variable. #8754

Merged
merged 4 commits into from
Apr 4, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 7 additions & 2 deletions xarray/core/variable.py
Original file line number Diff line number Diff line change
Expand Up @@ -247,8 +247,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 @@ -4908,7 +4908,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"])
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm unclear why this needs to be changed?

coordarr1 = coordarr0.copy()

hasna = np.isnan(minindex)
Expand Down Expand Up @@ -5023,7 +5023,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 @@ -7128,3 +7128,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)
Loading