MCPcopy Index your code
hub / github.com/pydata/xarray / _validate_attrs

Function _validate_attrs

xarray/backends/writers.py:103–162  ·  view source on GitHub ↗

`attrs` must have a string key and a value which is either: a number, a string, an ndarray, a list/tuple of numbers/strings, or a numpy.bool_. Notes ----- A numpy.bool_ is only allowed when using the h5netcdf engine with `invalid_netcdf=True`.

(dataset, engine, invalid_netcdf=False)

Source from the content-addressed store, hash-verified

101
102
103def _validate_attrs(dataset, engine, invalid_netcdf=False):
104 """`attrs` must have a string key and a value which is either: a number,
105 a string, an ndarray, a list/tuple of numbers/strings, or a numpy.bool_.
106
107 Notes
108 -----
109 A numpy.bool_ is only allowed when using the h5netcdf engine with
110 `invalid_netcdf=True`.
111 """
112
113 valid_types = (str, Number, np.ndarray, np.number, list, tuple, bytes)
114 if invalid_netcdf and engine == "h5netcdf":
115 valid_types += (np.bool_,)
116
117 def check_attr(name, value, valid_types):
118 if isinstance(name, str):
119 if not name:
120 raise ValueError(
121 f"Invalid name for attr {name!r}: string must be "
122 "length 1 or greater for serialization to "
123 "netCDF files"
124 )
125 else:
126 raise TypeError(
127 f"Invalid name for attr: {name!r} must be a string for "
128 "serialization to netCDF files"
129 )
130
131 if not isinstance(value, valid_types):
132 raise TypeError(
133 f"Invalid value for attr {name!r}: {value!r}. For serialization to "
134 "netCDF files, its value must be of one of the following types: "
135 f"{', '.join([vtype.__name__ for vtype in valid_types])}"
136 )
137
138 if isinstance(value, bytes) and engine == "h5netcdf":
139 try:
140 value.decode("utf-8")
141 except UnicodeDecodeError as e:
142 raise ValueError(
143 f"Invalid value provided for attribute '{name!r}': {value!r}. "
144 "Only binary data derived from UTF-8 encoded strings is allowed "
145 f"for the '{engine}' engine. Consider using the 'netcdf4' engine."
146 ) from e
147
148 if b"\x00" in value:
149 raise ValueError(
150 f"Invalid value provided for attribute '{name!r}': {value!r}. "
151 f"Null characters are not permitted for the '{engine}' engine. "
152 "Consider using the 'netcdf4' engine."
153 )
154
155 # Check attrs on the dataset itself
156 for k, v in dataset.attrs.items():
157 check_attr(k, v, valid_types)
158
159 # Check attrs on each variable within the dataset
160 for variable in dataset.variables.values():

Callers 1

to_netcdfFunction · 0.85

Calls 3

check_attrFunction · 0.85
itemsMethod · 0.80
valuesMethod · 0.45

Tested by

no test coverage detected

Used in the wild real call sites across dependent graphs

searching dependent graphs…