Check if a compression codec is available in the netCDF4 library. Parameters ---------- codec : str or None The compression codec name (e.g., 'zstd', 'blosc_lz', etc.) Returns ------- bool True if the codec is available, False otherwise.
(codec: str | None)
| 180 | |
| 181 | |
| 182 | def _check_compression_codec_available(codec: str | None) -> bool: |
| 183 | """Check if a compression codec is available in the netCDF4 library. |
| 184 | |
| 185 | Parameters |
| 186 | ---------- |
| 187 | codec : str or None |
| 188 | The compression codec name (e.g., 'zstd', 'blosc_lz', etc.) |
| 189 | |
| 190 | Returns |
| 191 | ------- |
| 192 | bool |
| 193 | True if the codec is available, False otherwise. |
| 194 | """ |
| 195 | if codec is None or codec in ("zlib", "szip"): |
| 196 | # These are standard and should be available |
| 197 | return True |
| 198 | |
| 199 | if not has_netCDF4: |
| 200 | return False |
| 201 | |
| 202 | try: |
| 203 | import os |
| 204 | |
| 205 | import netCDF4 |
| 206 | |
| 207 | # Try to create a file with the compression to test availability |
| 208 | with tempfile.NamedTemporaryFile(suffix=".nc", delete=False) as tmp: |
| 209 | tmp_path = tmp.name |
| 210 | |
| 211 | try: |
| 212 | nc = netCDF4.Dataset(tmp_path, "w", format="NETCDF4") |
| 213 | nc.createDimension("x", 10) |
| 214 | |
| 215 | # Attempt to create a variable with the compression |
| 216 | if codec and codec.startswith("blosc"): |
| 217 | nc.createVariable( # type: ignore[call-overload, unused-ignore] |
| 218 | varname="test", |
| 219 | datatype="f4", |
| 220 | dimensions=("x",), |
| 221 | compression=codec, |
| 222 | blosc_shuffle=1, |
| 223 | ) |
| 224 | else: |
| 225 | nc.createVariable( # type: ignore[call-overload, unused-ignore] |
| 226 | varname="test", datatype="f4", dimensions=("x",), compression=codec |
| 227 | ) |
| 228 | |
| 229 | nc.close() |
| 230 | os.unlink(tmp_path) |
| 231 | return True |
| 232 | except (RuntimeError, netCDF4.NetCDF4MissingFeatureException): |
| 233 | # Codec not available |
| 234 | if os.path.exists(tmp_path): |
| 235 | with contextlib.suppress(OSError): |
| 236 | os.unlink(tmp_path) |
| 237 | return False |
| 238 | except Exception: |
| 239 | # Any other error, assume codec is not available |
nothing calls this directly
no test coverage detected
searching dependent graphs…