Skip to content

Commit

Permalink
preserve boolean dtype in encoding (#7720)
Browse files Browse the repository at this point in the history
* preserve boolean-dtype within encoding, adapt test

* add comment as per review

* add whats-new.rst entry
  • Loading branch information
kmuehlbauer authored Apr 10, 2023
1 parent 8e899ad commit 5f39626
Show file tree
Hide file tree
Showing 3 changed files with 10 additions and 2 deletions.
3 changes: 2 additions & 1 deletion doc/whats-new.rst
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,8 @@ Bug fixes
(:issue:`7420`, :pull:`7441`).
By `Justus Magin <https://github.com/keewis>`_ and
`Spencer Clark <https://github.com/spencerkclark>`_.

- Preserve boolean dtype within encoding (:issue:`7652`, :pull:`7720`).
By `Kai Mühlbauer <https://github.com/kmuehlbauer>`_

Documentation
~~~~~~~~~~~~~
Expand Down
4 changes: 3 additions & 1 deletion xarray/coding/variables.py
Original file line number Diff line number Diff line change
Expand Up @@ -458,7 +458,9 @@ def encode(self, variable: Variable, name: T_Name = None) -> Variable:
def decode(self, variable: Variable, name: T_Name = None) -> Variable:
if variable.attrs.get("dtype", False) == "bool":
dims, data, attrs, encoding = unpack_for_decoding(variable)
del attrs["dtype"]
# overwrite (!) dtype in encoding, and remove from attrs
# needed for correct subsequent encoding
encoding["dtype"] = attrs.pop("dtype")
data = BoolTypeArray(data)
return Variable(dims, data, attrs, encoding, fastpath=True)
else:
Expand Down
5 changes: 5 additions & 0 deletions xarray/tests/test_backends.py
Original file line number Diff line number Diff line change
Expand Up @@ -630,6 +630,11 @@ def test_roundtrip_boolean_dtype(self) -> None:
with self.roundtrip(original) as actual:
assert_identical(original, actual)
assert actual["x"].dtype == "bool"
# this checks for preserving dtype during second roundtrip
# see https://github.com/pydata/xarray/issues/7652#issuecomment-1476956975
with self.roundtrip(actual) as actual2:
assert_identical(original, actual2)
assert actual2["x"].dtype == "bool"

def test_orthogonal_indexing(self) -> None:
in_memory = create_test_data()
Expand Down

0 comments on commit 5f39626

Please sign in to comment.