Skip to content

Commit 848d491

Browse files
dcherianshoyer
authored andcommitted
Deprecate inplace (#2524)
* Start deprecating inplace. * remove warnings from tests. * this commit silences nearly all warnings. * Add whats-new. * Add a default kwarg to _check_inplace and use for Dataset.update. * Major fix! * Add stacklevel * Tests: Less aggressive warning filter + fix unnecessary inplace. * revert changes to _calculate_binary_op
1 parent f788084 commit 848d491

File tree

7 files changed

+74
-41
lines changed

7 files changed

+74
-41
lines changed

doc/whats-new.rst

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -77,6 +77,9 @@ Documentation
7777
without dimension argument will change in the next release.
7878
Now we warn a FutureWarning.
7979
By `Keisuke Fujii <https://github.com/fujiisoup>`_.
80+
- The ``inplace`` kwarg of a number of `DataArray` and `Dataset` methods is being
81+
deprecated and will be removed in the next release.
82+
By `Deepak Cherian <https://github.com/dcherian>`_.
8083

8184
Enhancements
8285
~~~~~~~~~~~~

xarray/core/dataarray.py

Lines changed: 10 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,8 @@
1919
from .options import OPTIONS, _get_keep_attrs
2020
from .pycompat import OrderedDict, basestring, iteritems, range, zip
2121
from .utils import (
22-
decode_numpy_dict_values, either_dict_or_kwargs, ensure_us_time_resolution)
22+
_check_inplace, decode_numpy_dict_values, either_dict_or_kwargs,
23+
ensure_us_time_resolution)
2324
from .variable import (
2425
IndexVariable, Variable, as_compatible_data, as_variable,
2526
assert_unique_multiindex_level_names)
@@ -542,7 +543,7 @@ def coords(self):
542543
"""
543544
return DataArrayCoordinates(self)
544545

545-
def reset_coords(self, names=None, drop=False, inplace=False):
546+
def reset_coords(self, names=None, drop=False, inplace=None):
546547
"""Given names of coordinates, reset them to become variables.
547548
548549
Parameters
@@ -561,6 +562,7 @@ def reset_coords(self, names=None, drop=False, inplace=False):
561562
-------
562563
Dataset, or DataArray if ``drop == True``
563564
"""
565+
inplace = _check_inplace(inplace)
564566
if inplace and not drop:
565567
raise ValueError('cannot reset coordinates in-place on a '
566568
'DataArray without ``drop == True``')
@@ -1151,7 +1153,7 @@ def expand_dims(self, dim, axis=None):
11511153
ds = self._to_temp_dataset().expand_dims(dim, axis)
11521154
return self._from_temp_dataset(ds)
11531155

1154-
def set_index(self, indexes=None, append=False, inplace=False,
1156+
def set_index(self, indexes=None, append=False, inplace=None,
11551157
**indexes_kwargs):
11561158
"""Set DataArray (multi-)indexes using one or more existing
11571159
coordinates.
@@ -1181,14 +1183,15 @@ def set_index(self, indexes=None, append=False, inplace=False,
11811183
--------
11821184
DataArray.reset_index
11831185
"""
1186+
inplace = _check_inplace(inplace)
11841187
indexes = either_dict_or_kwargs(indexes, indexes_kwargs, 'set_index')
11851188
coords, _ = merge_indexes(indexes, self._coords, set(), append=append)
11861189
if inplace:
11871190
self._coords = coords
11881191
else:
11891192
return self._replace(coords=coords)
11901193

1191-
def reset_index(self, dims_or_levels, drop=False, inplace=False):
1194+
def reset_index(self, dims_or_levels, drop=False, inplace=None):
11921195
"""Reset the specified index(es) or multi-index level(s).
11931196
11941197
Parameters
@@ -1213,14 +1216,15 @@ def reset_index(self, dims_or_levels, drop=False, inplace=False):
12131216
--------
12141217
DataArray.set_index
12151218
"""
1219+
inplace = _check_inplace(inplace)
12161220
coords, _ = split_indexes(dims_or_levels, self._coords, set(),
12171221
self._level_coords, drop=drop)
12181222
if inplace:
12191223
self._coords = coords
12201224
else:
12211225
return self._replace(coords=coords)
12221226

1223-
def reorder_levels(self, dim_order=None, inplace=False,
1227+
def reorder_levels(self, dim_order=None, inplace=None,
12241228
**dim_order_kwargs):
12251229
"""Rearrange index levels using input order.
12261230
@@ -1243,6 +1247,7 @@ def reorder_levels(self, dim_order=None, inplace=False,
12431247
Another dataarray, with this dataarray's data but replaced
12441248
coordinates.
12451249
"""
1250+
inplace = _check_inplace(inplace)
12461251
dim_order = either_dict_or_kwargs(dim_order, dim_order_kwargs,
12471252
'reorder_levels')
12481253
replace_coords = {}

xarray/core/dataset.py

Lines changed: 21 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -32,9 +32,9 @@
3232
from .pycompat import (
3333
OrderedDict, basestring, dask_array_type, integer_types, iteritems, range)
3434
from .utils import (
35-
Frozen, SortedKeysDict, datetime_to_numeric, decode_numpy_dict_values,
36-
either_dict_or_kwargs, ensure_us_time_resolution, hashable,
37-
maybe_wrap_array)
35+
_check_inplace, Frozen, SortedKeysDict, datetime_to_numeric,
36+
decode_numpy_dict_values, either_dict_or_kwargs, ensure_us_time_resolution,
37+
hashable, maybe_wrap_array)
3838
from .variable import IndexVariable, Variable, as_variable, broadcast_variables
3939

4040
# list of attributes of pd.DatetimeIndex that are ndarrays of time info
@@ -1072,7 +1072,7 @@ def data_vars(self):
10721072
"""
10731073
return DataVariables(self)
10741074

1075-
def set_coords(self, names, inplace=False):
1075+
def set_coords(self, names, inplace=None):
10761076
"""Given names of one or more variables, set them as coordinates
10771077
10781078
Parameters
@@ -1095,14 +1095,15 @@ def set_coords(self, names, inplace=False):
10951095
# DataFrame.set_index?
10961096
# nb. check in self._variables, not self.data_vars to insure that the
10971097
# operation is idempotent
1098+
inplace = _check_inplace(inplace)
10981099
if isinstance(names, basestring):
10991100
names = [names]
11001101
self._assert_all_in_dataset(names)
11011102
obj = self if inplace else self.copy()
11021103
obj._coord_names.update(names)
11031104
return obj
11041105

1105-
def reset_coords(self, names=None, drop=False, inplace=False):
1106+
def reset_coords(self, names=None, drop=False, inplace=None):
11061107
"""Given names of coordinates, reset them to become variables
11071108
11081109
Parameters
@@ -1121,6 +1122,7 @@ def reset_coords(self, names=None, drop=False, inplace=False):
11211122
-------
11221123
Dataset
11231124
"""
1125+
inplace = _check_inplace(inplace)
11241126
if names is None:
11251127
names = self._coord_names - set(self.dims)
11261128
else:
@@ -2045,7 +2047,7 @@ def interp_like(self, other, method='linear', assume_sorted=False,
20452047
ds = self.reindex(object_coords)
20462048
return ds.interp(numeric_coords, method, assume_sorted, kwargs)
20472049

2048-
def rename(self, name_dict=None, inplace=False, **names):
2050+
def rename(self, name_dict=None, inplace=None, **names):
20492051
"""Returns a new object with renamed variables and dimensions.
20502052
20512053
Parameters
@@ -2070,6 +2072,7 @@ def rename(self, name_dict=None, inplace=False, **names):
20702072
Dataset.swap_dims
20712073
DataArray.rename
20722074
"""
2075+
inplace = _check_inplace(inplace)
20732076
name_dict = either_dict_or_kwargs(name_dict, names, 'rename')
20742077
for k, v in name_dict.items():
20752078
if k not in self and k not in self.dims:
@@ -2095,7 +2098,7 @@ def rename(self, name_dict=None, inplace=False, **names):
20952098
return self._replace_vars_and_dims(variables, coord_names, dims=dims,
20962099
inplace=inplace)
20972100

2098-
def swap_dims(self, dims_dict, inplace=False):
2101+
def swap_dims(self, dims_dict, inplace=None):
20992102
"""Returns a new object with swapped dimensions.
21002103
21012104
Parameters
@@ -2119,6 +2122,7 @@ def swap_dims(self, dims_dict, inplace=False):
21192122
Dataset.rename
21202123
DataArray.swap_dims
21212124
"""
2125+
inplace = _check_inplace(inplace)
21222126
for k, v in dims_dict.items():
21232127
if k not in self.dims:
21242128
raise ValueError('cannot swap from dimension %r because it is '
@@ -2231,7 +2235,7 @@ def expand_dims(self, dim, axis=None):
22312235

22322236
return self._replace_vars_and_dims(variables, self._coord_names)
22332237

2234-
def set_index(self, indexes=None, append=False, inplace=False,
2238+
def set_index(self, indexes=None, append=False, inplace=None,
22352239
**indexes_kwargs):
22362240
"""Set Dataset (multi-)indexes using one or more existing coordinates or
22372241
variables.
@@ -2262,14 +2266,15 @@ def set_index(self, indexes=None, append=False, inplace=False,
22622266
Dataset.reset_index
22632267
Dataset.swap_dims
22642268
"""
2269+
inplace = _check_inplace(inplace)
22652270
indexes = either_dict_or_kwargs(indexes, indexes_kwargs, 'set_index')
22662271
variables, coord_names = merge_indexes(indexes, self._variables,
22672272
self._coord_names,
22682273
append=append)
22692274
return self._replace_vars_and_dims(variables, coord_names=coord_names,
22702275
inplace=inplace)
22712276

2272-
def reset_index(self, dims_or_levels, drop=False, inplace=False):
2277+
def reset_index(self, dims_or_levels, drop=False, inplace=None):
22732278
"""Reset the specified index(es) or multi-index level(s).
22742279
22752280
Parameters
@@ -2293,13 +2298,14 @@ def reset_index(self, dims_or_levels, drop=False, inplace=False):
22932298
--------
22942299
Dataset.set_index
22952300
"""
2301+
inplace = _check_inplace(inplace)
22962302
variables, coord_names = split_indexes(dims_or_levels, self._variables,
22972303
self._coord_names,
22982304
self._level_coords, drop=drop)
22992305
return self._replace_vars_and_dims(variables, coord_names=coord_names,
23002306
inplace=inplace)
23012307

2302-
def reorder_levels(self, dim_order=None, inplace=False,
2308+
def reorder_levels(self, dim_order=None, inplace=None,
23032309
**dim_order_kwargs):
23042310
"""Rearrange index levels using input order.
23052311
@@ -2322,6 +2328,7 @@ def reorder_levels(self, dim_order=None, inplace=False,
23222328
Another dataset, with this dataset's data but replaced
23232329
coordinates.
23242330
"""
2331+
inplace = _check_inplace(inplace)
23252332
dim_order = either_dict_or_kwargs(dim_order, dim_order_kwargs,
23262333
'reorder_levels')
23272334
replace_variables = {}
@@ -2472,7 +2479,7 @@ def unstack(self, dim=None):
24722479
result = result._unstack_once(dim)
24732480
return result
24742481

2475-
def update(self, other, inplace=True):
2482+
def update(self, other, inplace=None):
24762483
"""Update this dataset's variables with those from another dataset.
24772484
24782485
Parameters
@@ -2494,12 +2501,13 @@ def update(self, other, inplace=True):
24942501
If any dimensions would have inconsistent sizes in the updated
24952502
dataset.
24962503
"""
2504+
inplace = _check_inplace(inplace, default=True)
24972505
variables, coord_names, dims = dataset_update_method(self, other)
24982506

24992507
return self._replace_vars_and_dims(variables, coord_names, dims,
25002508
inplace=inplace)
25012509

2502-
def merge(self, other, inplace=False, overwrite_vars=frozenset(),
2510+
def merge(self, other, inplace=None, overwrite_vars=frozenset(),
25032511
compat='no_conflicts', join='outer'):
25042512
"""Merge the arrays of two datasets into a single dataset.
25052513
@@ -2550,6 +2558,7 @@ def merge(self, other, inplace=False, overwrite_vars=frozenset(),
25502558
MergeError
25512559
If any variables conflict (see ``compat``).
25522560
"""
2561+
inplace = _check_inplace(inplace)
25532562
variables, coord_names, dims = dataset_merge_method(
25542563
self, other, overwrite_vars=overwrite_vars, compat=compat,
25552564
join=join)
@@ -3317,7 +3326,6 @@ def func(self, other):
33173326

33183327
def _calculate_binary_op(self, f, other, join='inner',
33193328
inplace=False):
3320-
33213329
def apply_over_both(lhs_data_vars, rhs_data_vars, lhs_vars, rhs_vars):
33223330
if inplace and set(lhs_data_vars) != set(rhs_data_vars):
33233331
raise ValueError('datasets must have the same data variables '

xarray/core/utils.py

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,16 @@
1717
OrderedDict, basestring, bytes_type, dask_array_type, iteritems)
1818

1919

20+
def _check_inplace(inplace, default=False):
21+
if inplace is None:
22+
inplace = default
23+
else:
24+
warnings.warn('The inplace argument has been deprecated and will be '
25+
'removed in xarray 0.12.0.', FutureWarning, stacklevel=3)
26+
27+
return inplace
28+
29+
2030
def alias_message(old_name, new_name):
2131
return '%s has been deprecated. Use %s instead.' % (old_name, new_name)
2232

xarray/tests/test_dataarray.py

Lines changed: 10 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1155,7 +1155,7 @@ def test_reset_coords(self):
11551155
assert_identical(actual, expected)
11561156

11571157
actual = data.copy()
1158-
actual.reset_coords(drop=True, inplace=True)
1158+
actual = actual.reset_coords(drop=True)
11591159
assert_identical(actual, expected)
11601160

11611161
actual = data.reset_coords('bar', drop=True)
@@ -1164,8 +1164,9 @@ def test_reset_coords(self):
11641164
dims=['x', 'y'], name='foo')
11651165
assert_identical(actual, expected)
11661166

1167-
with raises_regex(ValueError, 'cannot reset coord'):
1168-
data.reset_coords(inplace=True)
1167+
with pytest.warns(FutureWarning, message='The inplace argument'):
1168+
with raises_regex(ValueError, 'cannot reset coord'):
1169+
data = data.reset_coords(inplace=True)
11691170
with raises_regex(ValueError, 'cannot be found'):
11701171
data.reset_coords('foo', drop=True)
11711172
with raises_regex(ValueError, 'cannot be found'):
@@ -1398,7 +1399,7 @@ def test_set_index(self):
13981399
expected = array.set_index(x=['level_1', 'level_2', 'level_3'])
13991400
assert_identical(obj, expected)
14001401

1401-
array.set_index(x=['level_1', 'level_2', 'level_3'], inplace=True)
1402+
array = array.set_index(x=['level_1', 'level_2', 'level_3'])
14021403
assert_identical(array, expected)
14031404

14041405
array2d = DataArray(np.random.rand(2, 2),
@@ -1431,7 +1432,7 @@ def test_reset_index(self):
14311432
assert_identical(obj, expected)
14321433

14331434
array = self.mda.copy()
1434-
array.reset_index(['x'], drop=True, inplace=True)
1435+
array = array.reset_index(['x'], drop=True)
14351436
assert_identical(array, expected)
14361437

14371438
# single index
@@ -1447,9 +1448,10 @@ def test_reorder_levels(self):
14471448
obj = self.mda.reorder_levels(x=['level_2', 'level_1'])
14481449
assert_identical(obj, expected)
14491450

1450-
array = self.mda.copy()
1451-
array.reorder_levels(x=['level_2', 'level_1'], inplace=True)
1452-
assert_identical(array, expected)
1451+
with pytest.warns(FutureWarning, message='The inplace argument'):
1452+
array = self.mda.copy()
1453+
array.reorder_levels(x=['level_2', 'level_1'], inplace=True)
1454+
assert_identical(array, expected)
14531455

14541456
array = DataArray([1, 2], dims='x')
14551457
with pytest.raises(KeyError):

0 commit comments

Comments
 (0)