Skip to content

Commit 26f1b32

Browse files
committed
Add built-in dictionary for dtype to default fill value
1 parent 4ebfb4d commit 26f1b32

File tree

2 files changed

+23
-5
lines changed

2 files changed

+23
-5
lines changed

xarray/coding/variables.py

Lines changed: 21 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -3,14 +3,27 @@
33
from functools import partial
44
from typing import Any, Hashable
55

6-
import netCDF4
76
import numpy as np
87
import pandas as pd
98

109
from ..core import dtypes, duck_array_ops, indexing
1110
from ..core.pycompat import is_duck_dask_array
1211
from ..core.variable import Variable
1312

13+
NP_TO_NC_TYPE = {
14+
"S1": "\x00",
15+
"i1": -127,
16+
"u1": 255,
17+
"i2": -32767,
18+
"u2": 65535,
19+
"i4": -2147483647,
20+
"u4": 4294967295,
21+
"i8": -9223372036854775806,
22+
"u8": 18446744073709551614,
23+
"f4": 9.969209968386869e36,
24+
"f8": 9.969209968386869e36,
25+
}
26+
1427

1528
class SerializationWarning(RuntimeWarning):
1629
"""Warnings about encoding/decoding issues in serialization."""
@@ -184,8 +197,14 @@ def decode(self, variable, name=None):
184197
pop_to(attrs, encoding, attr, name=name)
185198
for attr in ("missing_value", "_FillValue")
186199
]
200+
try:
201+
default_fillvalue = NP_TO_NC_TYPE[np.dtype(variable.dtype).str[1:]]
202+
raw_fill_values.append(default_fillvalue)
203+
except KeyError:
204+
warnings.warn(
205+
f"A default fill value for dtype {variable.dtype} could not be found"
206+
)
187207

188-
raw_fill_values.append(netCDF4.default_fillvals["f8"])
189208
if raw_fill_values:
190209
encoded_fill_values = {
191210
fv
@@ -212,7 +231,6 @@ def decode(self, variable, name=None):
212231
dtype=dtype,
213232
)
214233
data = lazy_elemwise_func(data, transform, dtype)
215-
216234
return Variable(dims, data, attrs, encoding)
217235

218236

xarray/tests/test_conventions.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,6 @@
11
import contextlib
22
import warnings
33

4-
import netCDF4
54
import numpy as np
65
import pandas as pd
76
import pytest
@@ -234,7 +233,8 @@ def test_decode_cf_with_multiple_missing_values(self):
234233
assert "has multiple fill" in str(w[0].message)
235234

236235
def test_decode_standard_missing_value(self):
237-
original = Variable(["t"], [netCDF4.default_fillvals["f8"], 1, 2], {})
236+
237+
original = Variable(["t"], [coding.variables.NP_TO_NC_TYPE["f8"], 1, 2], {})
238238
expected = Variable(["t"], [np.nan, 1, 2], {})
239239
actual = conventions.decode_cf_variable("t", original)
240240
assert_identical(expected, actual)

0 commit comments

Comments
 (0)