Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix CF writer crashing with netcdf development version #2961

Merged
merged 2 commits into from
Nov 4, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 10 additions & 3 deletions satpy/tests/writer_tests/test_cf.py
Original file line number Diff line number Diff line change
Expand Up @@ -528,12 +528,19 @@ def _assert_encoding_as_expected(self, filename, expected):
assert f["test-array"].dtype == expected["dtype"]
assert f["test-array"].encoding["complevel"] == expected["complevel"]

def test_warning_if_backends_dont_match(self, scene, filename, monkeypatch):
@pytest.mark.parametrize(
"versions",
[
{"netCDF4": "1.5.0", "libnetcdf": "4.9.1-development"},
{"netCDF4": "1.6.0", "libnetcdf": "invalid-version"}
]
)
def test_warning_if_backends_dont_match(self, scene, filename, monkeypatch, versions):
"""Test warning if backends don't match."""
import netCDF4
with monkeypatch.context() as m:
m.setattr(netCDF4, "__version__", "1.5.0")
m.setattr(netCDF4, "__netcdf4libversion__", "4.9.1")
m.setattr(netCDF4, "__version__", versions["netCDF4"])
m.setattr(netCDF4, "__netcdf4libversion__", versions["libnetcdf"])
with pytest.warns(UserWarning, match=r"Backend version mismatch"):
scene.save_datasets(filename=filename, writer="cf")

Expand Down
22 changes: 20 additions & 2 deletions satpy/writers/cf_writer.py
Original file line number Diff line number Diff line change
Expand Up @@ -158,7 +158,7 @@

import numpy as np
import xarray as xr
from packaging.version import Version
from packaging.version import InvalidVersion, Version

from satpy.cf.coords import EPOCH # noqa: F401 (for backward compatibility)
from satpy.writers import Writer
Expand Down Expand Up @@ -390,8 +390,26 @@ def _backend_versions_match():

def _get_backend_versions():
import netCDF4
libnetcdf_version = _parse_libnetcdf_version(
netCDF4.__netcdf4libversion__
)
return {
"netCDF4": Version(netCDF4.__version__),
"libnetcdf": Version(netCDF4.__netcdf4libversion__),
"libnetcdf": libnetcdf_version,
"xarray": Version(xr.__version__)
}


def _parse_libnetcdf_version(version_str):
# Make libnetcdf development version compatible with PEP440
version_str = version_str.replace("development", "dev")
try:
return Version(version_str)
except InvalidVersion:
warnings.warn(
f"Unable to parse netcdf-c version {version_str}, "
f"using 0.0.0 as fallback",
UserWarning,
stacklevel=3
)
return Version("0.0.0")
Loading