Skip to content

Commit 5f39626

Browse files
authored
preserve boolean dtype in encoding (#7720)
* preserve boolean-dtype within encoding, adapt test * add comment as per review * add whats-new.rst entry
1 parent 8e899ad commit 5f39626

File tree

3 files changed

+10
-2
lines changed

3 files changed

+10
-2
lines changed

doc/whats-new.rst

+2-1
Original file line numberDiff line numberDiff line change
@@ -54,7 +54,8 @@ Bug fixes
5454
(:issue:`7420`, :pull:`7441`).
5555
By `Justus Magin <https://github.com/keewis>`_ and
5656
`Spencer Clark <https://github.com/spencerkclark>`_.
57-
57+
- Preserve boolean dtype within encoding (:issue:`7652`, :pull:`7720`).
58+
By `Kai Mühlbauer <https://github.com/kmuehlbauer>`_
5859

5960
Documentation
6061
~~~~~~~~~~~~~

xarray/coding/variables.py

+3-1
Original file line numberDiff line numberDiff line change
@@ -458,7 +458,9 @@ def encode(self, variable: Variable, name: T_Name = None) -> Variable:
458458
def decode(self, variable: Variable, name: T_Name = None) -> Variable:
459459
if variable.attrs.get("dtype", False) == "bool":
460460
dims, data, attrs, encoding = unpack_for_decoding(variable)
461-
del attrs["dtype"]
461+
# overwrite (!) dtype in encoding, and remove from attrs
462+
# needed for correct subsequent encoding
463+
encoding["dtype"] = attrs.pop("dtype")
462464
data = BoolTypeArray(data)
463465
return Variable(dims, data, attrs, encoding, fastpath=True)
464466
else:

xarray/tests/test_backends.py

+5
Original file line numberDiff line numberDiff line change
@@ -630,6 +630,11 @@ def test_roundtrip_boolean_dtype(self) -> None:
630630
with self.roundtrip(original) as actual:
631631
assert_identical(original, actual)
632632
assert actual["x"].dtype == "bool"
633+
# this checks for preserving dtype during second roundtrip
634+
# see https://github.com/pydata/xarray/issues/7652#issuecomment-1476956975
635+
with self.roundtrip(actual) as actual2:
636+
assert_identical(original, actual2)
637+
assert actual2["x"].dtype == "bool"
633638

634639
def test_orthogonal_indexing(self) -> None:
635640
in_memory = create_test_data()

0 commit comments

Comments
 (0)