Skip to content

Commit 8b24037

Browse files
authored
add Variable._replace (#3528)
* add Variable._replace * assertions * whatsew * whatsnew
1 parent 4358762 commit 8b24037

File tree

3 files changed

+29
-2
lines changed

3 files changed

+29
-2
lines changed

doc/whats-new.rst

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -138,6 +138,9 @@ Internal Changes
138138
- Enable type checking on default sentinel values (:pull:`3472`)
139139
By `Maximilian Roos <https://github.com/max-sixty>`_
140140

141+
- Add :py:meth:`Variable._replace` for simpler replacing of a subset of attributes (:pull:`3472`)
142+
By `Maximilian Roos <https://github.com/max-sixty>`_
143+
141144
.. _whats-new.0.14.0:
142145

143146
v0.14.0 (14 Oct 2019)

xarray/core/variable.py

Lines changed: 17 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import copy
12
import functools
23
import itertools
34
import warnings
@@ -24,10 +25,11 @@
2425
from .pycompat import dask_array_type, integer_types
2526
from .utils import (
2627
OrderedSet,
28+
_default,
2729
decode_numpy_dict_values,
2830
either_dict_or_kwargs,
29-
infix_dims,
3031
ensure_us_time_resolution,
32+
infix_dims,
3133
)
3234

3335
try:
@@ -887,7 +889,20 @@ def copy(self, deep=True, data=None):
887889
# note:
888890
# dims is already an immutable tuple
889891
# attributes and encoding will be copied when the new Array is created
890-
return type(self)(self.dims, data, self._attrs, self._encoding, fastpath=True)
892+
return self._replace(data=data)
893+
894+
def _replace(
895+
self, dims=_default, data=_default, attrs=_default, encoding=_default
896+
) -> "Variable":
897+
if dims is _default:
898+
dims = copy.copy(self._dims)
899+
if data is _default:
900+
data = copy.copy(self.data)
901+
if attrs is _default:
902+
attrs = copy.copy(self._attrs)
903+
if encoding is _default:
904+
encoding = copy.copy(self._encoding)
905+
return type(self)(dims, data, attrs, encoding, fastpath=True)
891906

892907
def __copy__(self):
893908
return self.copy(deep=False)

xarray/tests/test_variable.py

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -542,6 +542,15 @@ def test_copy_index_with_data_errors(self):
542542
with raises_regex(ValueError, "must match shape of object"):
543543
orig.copy(data=new_data)
544544

545+
def test_replace(self):
546+
var = Variable(("x", "y"), [[1.5, 2.0], [3.1, 4.3]], {"foo": "bar"})
547+
result = var._replace()
548+
assert_identical(result, var)
549+
550+
new_data = np.arange(4).reshape(2, 2)
551+
result = var._replace(data=new_data)
552+
assert_array_equal(result.data, new_data)
553+
545554
def test_real_and_imag(self):
546555
v = self.cls("x", np.arange(3) - 1j * np.arange(3), {"foo": "bar"})
547556
expected_re = self.cls("x", np.arange(3), {"foo": "bar"})

0 commit comments

Comments
 (0)