Skip to content

Commit 7e4ccfb

Browse files
chunhochowkeewis
andauthored
variable.py as_compatible_data: disallow DataArrays (pydata#4493)
* variable.py as_compatible_data: allow DataArrays too * variable.py: as_compatible_data: DataArray raise TypeError tell user to use da.data * variable.py: as_compatible_data: debug syntax * variable.py: update no .data error msg * move err msg to as_variable * whats-new changelog * stylistic debug * whats-new.rst move changelog to new unreleased version * debug formatting whats-new.rst * add .data to tests using tuples * fix test_dask.py test * fix test_dataset * raise DeprecationWarning instead of TypeError * add .data to the example in plotting * state when the warning will be turned into an error * small fix [skip-ci] * check that as_variable warns correctly * warn instead of raising the warning * fix the test * manually extract the data * use a single statement to modify obj * remove the extraction of the data altogether Co-authored-by: chunhochow <[email protected]> Co-authored-by: Keewis <[email protected]>
1 parent 9a4313b commit 7e4ccfb

File tree

7 files changed

+22
-6
lines changed

7 files changed

+22
-6
lines changed

doc/plotting.rst

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -227,7 +227,7 @@ from the time and assign it as a non-dimension coordinate:
227227
:okwarning:
228228
229229
decimal_day = (air1d.time - air1d.time[0]) / pd.Timedelta("1d")
230-
air1d_multi = air1d.assign_coords(decimal_day=("time", decimal_day))
230+
air1d_multi = air1d.assign_coords(decimal_day=("time", decimal_day.data))
231231
air1d_multi
232232
233233
To use ``'decimal_day'`` as x coordinate it must be explicitly specified:

doc/whats-new.rst

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -128,6 +128,9 @@ Bug fixes
128128
- Expand user directory paths (e.g. ``~/``) in :py:func:`open_mfdataset` and
129129
:py:meth:`Dataset.to_zarr` (:issue:`4783`, :pull:`4795`).
130130
By `Julien Seguinot <https://github.com/juseg>`_.
131+
- Raise DeprecationWarning when trying to typecast a tuple containing a :py:class:`DataArray`.
132+
User now prompted to first call `.data` on it (:issue:`4483`).
133+
By `Chun Ho Chow <https://github.com/chunhochow>`_.
131134
- Add :py:meth:`Dataset.drop_isel` and :py:meth:`DataArray.drop_isel` (:issue:`4658`, :pull:`4819`). By `Daniel Mesejo <https://github.com/mesejo>`_.
132135
- Ensure that :py:meth:`Dataset.interp` raises ``ValueError`` when interpolating outside coordinate range and ``bounds_error=True`` (:issue:`4854`, :pull:`4855`).
133136
By `Leif Denby <https://github.com/leifdenby>`_.

xarray/core/variable.py

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -120,6 +120,16 @@ def as_variable(obj, name=None) -> "Union[Variable, IndexVariable]":
120120
if isinstance(obj, Variable):
121121
obj = obj.copy(deep=False)
122122
elif isinstance(obj, tuple):
123+
if isinstance(obj[1], DataArray):
124+
# TODO: change into TypeError
125+
warnings.warn(
126+
(
127+
"Using a DataArray object to construct a variable is"
128+
" ambiguous, please extract the data using the .data property."
129+
" This will raise a TypeError in 0.19.0."
130+
),
131+
DeprecationWarning,
132+
)
123133
try:
124134
obj = Variable(*obj)
125135
except (TypeError, ValueError) as error:

xarray/tests/test_dask.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1233,7 +1233,7 @@ def test_map_blocks_to_array(map_ds):
12331233
lambda x: x.drop_vars("x"),
12341234
lambda x: x.expand_dims(k=[1, 2, 3]),
12351235
lambda x: x.expand_dims(k=3),
1236-
lambda x: x.assign_coords(new_coord=("y", x.y * 2)),
1236+
lambda x: x.assign_coords(new_coord=("y", x.y.data * 2)),
12371237
lambda x: x.astype(np.int32),
12381238
lambda x: x.x,
12391239
],

xarray/tests/test_dataset.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4959,13 +4959,13 @@ def test_reduce_keepdims(self):
49594959
# Coordinates involved in the reduction should be removed
49604960
actual = ds.mean(keepdims=True)
49614961
expected = Dataset(
4962-
{"a": (["x", "y"], np.mean(ds.a, keepdims=True))}, coords={"c": ds.c}
4962+
{"a": (["x", "y"], np.mean(ds.a, keepdims=True).data)}, coords={"c": ds.c}
49634963
)
49644964
assert_identical(expected, actual)
49654965

49664966
actual = ds.mean("x", keepdims=True)
49674967
expected = Dataset(
4968-
{"a": (["x", "y"], np.mean(ds.a, axis=0, keepdims=True))},
4968+
{"a": (["x", "y"], np.mean(ds.a, axis=0, keepdims=True).data)},
49694969
coords={"y": ds.y, "c": ds.c},
49704970
)
49714971
assert_identical(expected, actual)

xarray/tests/test_interp.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -190,7 +190,7 @@ def func(obj, dim, new_x):
190190
"w": xdest["w"],
191191
"z2": xdest["z2"],
192192
"y": da["y"],
193-
"x": (("z", "w"), xdest),
193+
"x": (("z", "w"), xdest.data),
194194
"x2": (("z", "w"), func(da["x2"], "x", xdest)),
195195
},
196196
)

xarray/tests/test_variable.py

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@
88
import pytest
99
import pytz
1010

11-
from xarray import Coordinate, Dataset, IndexVariable, Variable, set_options
11+
from xarray import Coordinate, DataArray, Dataset, IndexVariable, Variable, set_options
1212
from xarray.core import dtypes, duck_array_ops, indexing
1313
from xarray.core.common import full_like, ones_like, zeros_like
1414
from xarray.core.indexing import (
@@ -1081,6 +1081,9 @@ def test_as_variable(self):
10811081
td = np.array([timedelta(days=x) for x in range(10)])
10821082
assert as_variable(td, "time").dtype.kind == "m"
10831083

1084+
with pytest.warns(DeprecationWarning):
1085+
as_variable(("x", DataArray([])))
1086+
10841087
def test_repr(self):
10851088
v = Variable(["time", "x"], [[1, 2, 3], [4, 5, 6]], {"foo": "bar"})
10861089
expected = dedent(

0 commit comments

Comments
 (0)