Skip to content
8 changes: 7 additions & 1 deletion xarray/indexes/nd_point_index.py
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,13 @@ class ScipyKDTreeAdapter(TreeAdapter):
_kdtree: KDTree

def __init__(self, points: np.ndarray, options: Mapping[str, Any]):
from scipy.spatial import KDTree
try:
from scipy.spatial import KDTree
except ImportError as err:
raise ImportError(
"`NDPointIndex` requires `scipy` when used with `ScipyKDTreeAdapter`. "
"Please ensure that `scipy` is installed and importable."
) from err
Comment on lines +81 to +84
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

So I understand, is the only way to hit this error trying to import the defuault NDPointIndex without scipy installed?

Since there are other possible trees, not all of which necessarily require scipy, is there any those escape this warning?

Copy link
Collaborator

@keewis keewis Jan 14, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

NDPointIndex is a generalized class that delegates to a TreeAdapter subclass, which does the import. Thus, every adapter needs to raise its own error if the corresponding optional dependency is missing.

For example, the adapters in xoak would have to raise if sklearn or pys2index are missing.


self._kdtree = KDTree(points, **options)

Expand Down
13 changes: 13 additions & 0 deletions xarray/tests/test_nd_point_index_missing_scipy.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import numpy as np
import pytest

from xarray.indexes.nd_point_index import ScipyKDTreeAdapter
from xarray.tests import has_scipy


@pytest.mark.skipif(has_scipy, reason="requires scipy to be missing")
def test_scipy_kdtree_adapter_missing_scipy():
points = np.random.rand(4, 2)

with pytest.raises(ImportError, match=r"scipy"):
ScipyKDTreeAdapter(points, options={})
Loading