Skip to content

Commit a57c591

Browse files
committed
typing
1 parent c3e7a48 commit a57c591

File tree

11 files changed

+61
-60
lines changed

11 files changed

+61
-60
lines changed

pyproject.toml

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -125,6 +125,7 @@ module = [
125125
"netCDF4.*",
126126
"netcdftime.*",
127127
"opt_einsum.*",
128+
"pandas.*",
128129
"pint.*",
129130
"pooch.*",
130131
"pyarrow.*",
@@ -178,7 +179,7 @@ module = [
178179
"xarray.tests.test_units",
179180
"xarray.tests.test_utils",
180181
"xarray.tests.test_variable",
181-
"xarray.tests.test_weighted",
182+
"xarray.tests.test_weighted"
182183
]
183184

184185
# Use strict = true whenever namedarray has become standalone. In the meantime

xarray/coding/cftimeindex.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -517,7 +517,7 @@ def contains(self, key: Any) -> bool:
517517
"""Needed for .loc based partial-string indexing"""
518518
return self.__contains__(key)
519519

520-
def shift( # type: ignore[override] # freq is typed Any, we are more precise
520+
def shift( # freq is typed Any, we are more precise
521521
self,
522522
periods: int | float,
523523
freq: str | timedelta | BaseCFTimeOffset | None = None,

xarray/core/dataarray.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3033,7 +3033,7 @@ def to_unstacked_dataset(self, dim: Hashable, level: int | Hashable = 0) -> Data
30333033
if not isinstance(idx, pd.MultiIndex):
30343034
raise ValueError(f"'{dim}' is not a stacked coordinate")
30353035

3036-
level_number = idx._get_level_number(level) # type: ignore[attr-defined]
3036+
level_number = idx._get_level_number(level)
30373037
variables = idx.levels[level_number]
30383038
variable_dim = idx.names[level_number]
30393039

xarray/core/dataset.py

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -6629,7 +6629,7 @@ def interpolate_na(
66296629
| None
66306630
) = None,
66316631
**kwargs: Any,
6632-
) -> Self:
6632+
) -> Dataset:
66336633
"""Fill in NaNs by interpolating according to different methods.
66346634
66356635
Parameters
@@ -6760,7 +6760,7 @@ def interpolate_na(
67606760
)
67616761
return new
67626762

6763-
def ffill(self, dim: Hashable, limit: int | None = None) -> Self:
6763+
def ffill(self, dim: Hashable, limit: int | None = None) -> Dataset:
67646764
"""Fill NaN values by propagating values forward
67656765
67666766
*Requires bottleneck.*
@@ -6824,7 +6824,7 @@ def ffill(self, dim: Hashable, limit: int | None = None) -> Self:
68246824
new = _apply_over_vars_with_dim(ffill, self, dim=dim, limit=limit)
68256825
return new
68266826

6827-
def bfill(self, dim: Hashable, limit: int | None = None) -> Self:
6827+
def bfill(self, dim: Hashable, limit: int | None = None) -> Dataset:
68286828
"""Fill NaN values by propagating values backward
68296829
68306830
*Requires bottleneck.*
@@ -7523,7 +7523,7 @@ def from_dataframe(cls, dataframe: pd.DataFrame, sparse: bool = False) -> Self:
75237523

75247524
if isinstance(idx, pd.MultiIndex):
75257525
dims = tuple(
7526-
name if name is not None else "level_%i" % n # type: ignore[redundant-expr]
7526+
name if name is not None else "level_%i" % n
75277527
for n, name in enumerate(idx.names)
75287528
)
75297529
for dim, lev in zip(dims, idx.levels, strict=True):
@@ -9817,7 +9817,7 @@ def eval(
98179817
c (x) float64 40B 0.0 1.25 2.5 3.75 5.0
98189818
"""
98199819

9820-
return pd.eval( # type: ignore[return-value]
9820+
return pd.eval(
98219821
statement,
98229822
resolvers=[self],
98239823
target=self,

xarray/core/extension_array.py

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -45,7 +45,7 @@ def __extension_duck_array__stack(arr: T_ExtensionArray, axis: int):
4545
def __extension_duck_array__concatenate(
4646
arrays: Sequence[T_ExtensionArray], axis: int = 0, out=None
4747
) -> T_ExtensionArray:
48-
return type(arrays[0])._concat_same_type(arrays) # type: ignore[attr-defined]
48+
return type(arrays[0])._concat_same_type(arrays)
4949

5050

5151
@implements(np.where)
@@ -57,8 +57,8 @@ def __extension_duck_array__where(
5757
and isinstance(y, pd.Categorical)
5858
and x.dtype != y.dtype
5959
):
60-
x = x.add_categories(set(y.categories).difference(set(x.categories))) # type: ignore[assignment]
61-
y = y.add_categories(set(x.categories).difference(set(y.categories))) # type: ignore[assignment]
60+
x = x.add_categories(set(y.categories).difference(set(x.categories)))
61+
y = y.add_categories(set(x.categories).difference(set(y.categories)))
6262
return cast(T_ExtensionArray, pd.Series(x).where(condition, pd.Series(y)).array)
6363

6464

@@ -116,7 +116,9 @@ def __getitem__(self, key) -> PandasExtensionArray[T_ExtensionArray]:
116116
if is_extension_array_dtype(item):
117117
return type(self)(item)
118118
if np.isscalar(item):
119-
return type(self)(type(self.array)([item])) # type: ignore[call-arg] # only subclasses with proper __init__ allowed
119+
return type(self)(
120+
type(self.array)([item])
121+
) # only subclasses with proper __init__ allowed
120122
return item
121123

122124
def __setitem__(self, key, val):

xarray/core/indexes.py

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -740,7 +740,7 @@ def isel(
740740
# scalar indexer: drop index
741741
return None
742742

743-
return self._replace(self.index[indxr]) # type: ignore[index]
743+
return self._replace(self.index[indxr])
744744

745745
def sel(
746746
self, labels: dict[Any, Any], method=None, tolerance=None
@@ -926,7 +926,7 @@ def remove_unused_levels_categories(index: T_PDIndex) -> T_PDIndex:
926926
return cast(T_PDIndex, new_index)
927927

928928
if isinstance(index, pd.CategoricalIndex):
929-
return index.remove_unused_categories() # type: ignore[attr-defined]
929+
return index.remove_unused_categories()
930930

931931
return index
932932

@@ -1164,7 +1164,7 @@ def create_variables(
11641164
dtype = None
11651165
else:
11661166
level = name
1167-
dtype = self.level_coords_dtype[name] # type: ignore[index] # TODO: are Hashables ok?
1167+
dtype = self.level_coords_dtype[name] # TODO: are Hashables ok?
11681168

11691169
var = variables.get(name, None)
11701170
if var is not None:
@@ -1174,7 +1174,9 @@ def create_variables(
11741174
attrs = {}
11751175
encoding = {}
11761176

1177-
data = PandasMultiIndexingAdapter(self.index, dtype=dtype, level=level) # type: ignore[arg-type] # TODO: are Hashables ok?
1177+
data = PandasMultiIndexingAdapter(
1178+
self.index, dtype=dtype, level=level
1179+
) # TODO: are Hashables ok?
11781180
index_vars[name] = IndexVariable(
11791181
self.dim,
11801182
data,
@@ -1671,7 +1673,7 @@ def copy_indexes(
16711673
convert_new_idx = False
16721674
xr_idx = idx
16731675

1674-
new_idx = xr_idx._copy(deep=deep, memo=memo) # type: ignore[assignment]
1676+
new_idx = xr_idx._copy(deep=deep, memo=memo)
16751677
idx_vars = xr_idx.create_variables(coords)
16761678

16771679
if convert_new_idx:

xarray/core/missing.py

Lines changed: 31 additions & 35 deletions
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,6 @@
2929
if TYPE_CHECKING:
3030
from xarray.core.dataarray import DataArray
3131
from xarray.core.dataset import Dataset
32-
from xarray.core.variable import IndexVariable
3332

3433

3534
def _get_nan_block_lengths(
@@ -146,7 +145,7 @@ def __init__(
146145
copy: bool = False,
147146
bounds_error: bool = False,
148147
order: Optional[int] = None,
149-
axis=-1,
148+
axis: int = -1,
150149
**kwargs,
151150
):
152151
from scipy.interpolate import interp1d
@@ -167,8 +166,6 @@ def __init__(
167166
self.cons_kwargs = kwargs
168167
self.call_kwargs = {}
169168

170-
nan = np.nan if yi.dtype.kind != "c" else np.nan + np.nan * 1j
171-
172169
self.f = interp1d(
173170
xi,
174171
yi,
@@ -192,13 +189,13 @@ class SplineInterpolator(BaseInterpolator):
192189

193190
def __init__(
194191
self,
195-
xi,
196-
yi,
197-
method="spline",
198-
fill_value=None,
199-
order=3,
200-
nu=0,
201-
ext=None,
192+
xi: Variable,
193+
yi: np.ndarray,
194+
method: Optional[str | int] = "spline",
195+
fill_value: Optional[float | complex] = None,
196+
order: int = 3,
197+
nu: Optional[float] = 0,
198+
ext: Optional[int | str] = None,
202199
**kwargs,
203200
):
204201
from scipy.interpolate import UnivariateSpline
@@ -216,7 +213,9 @@ def __init__(
216213
self.f = UnivariateSpline(xi, yi, k=order, **self.cons_kwargs)
217214

218215

219-
def _apply_over_vars_with_dim(func, self, dim=None, **kwargs):
216+
def _apply_over_vars_with_dim(
217+
func: Callable, self: Dataset, dim: Optional[Hashable] = None, **kwargs
218+
) -> Dataset:
220219
"""Wrapper for datasets"""
221220
ds = type(self)(coords=self.coords, attrs=self.attrs)
222221

@@ -606,7 +605,7 @@ def _floatize_x(x, new_x):
606605

607606
def interp(
608607
var: Variable,
609-
indexes_coords: dict[str, IndexVariable],
608+
indexes_coords: dict[Hashable, tuple[Any, Any]],
610609
method: InterpOptions,
611610
**kwargs,
612611
) -> Variable:
@@ -671,9 +670,9 @@ def interp(
671670

672671

673672
def interp_func(
674-
var: np.ndarray,
675-
x: list[IndexVariable],
676-
new_x: list[IndexVariable],
673+
var: DataArray,
674+
x: tuple[Variable, ...],
675+
new_x: tuple[Variable, ...],
677676
method: InterpOptions,
678677
kwargs: dict,
679678
) -> np.ndarray:
@@ -683,13 +682,10 @@ def interp_func(
683682
684683
Parameters
685684
----------
686-
var : np.ndarray or dask.array.Array
687-
Array to be interpolated. The final dimension is interpolated.
688-
x : a list of 1d array.
689-
Original coordinates. Should not contain NaN.
690-
new_x : a list of 1d array
691-
New coordinates. Should not contain NaN.
692-
method : string
685+
var : Array to be interpolated. The final dimension is interpolated.
686+
x : Original coordinates. Should not contain NaN.
687+
new_x : New coordinates. Should not contain NaN.
688+
method :
693689
{'linear', 'nearest', 'zero', 'slinear', 'quadratic', 'cubic', 'pchip', 'akima',
694690
'makima', 'barycentric', 'krogh'} for 1-dimensional interpolation.
695691
{'linear', 'nearest'} for multidimensional interpolation
@@ -710,7 +706,7 @@ def interp_func(
710706
scipy.interpolate.interp1d
711707
"""
712708
if not x:
713-
return var.copy()
709+
return var.data.copy()
714710

715711
if len(x) == 1:
716712
func, kwargs = _get_interpolator(method, vectorizeable_only=True, **kwargs)
@@ -727,11 +723,11 @@ def interp_func(
727723

728724
# blockwise args format
729725
x_arginds = [[_x, (nconst + index,)] for index, _x in enumerate(x)]
730-
x_arginds = [item for pair in x_arginds for item in pair]
726+
x_arginds = [item for pair in x_arginds for item in pair] # type: ignore[misc]
731727
new_x_arginds = [
732728
[_x, [ndim + index for index in range(_x.ndim)]] for _x in new_x
733729
]
734-
new_x_arginds = [item for pair in new_x_arginds for item in pair]
730+
new_x_arginds = [item for pair in new_x_arginds for item in pair] # type: ignore[misc]
735731

736732
args = (var, range(ndim), *x_arginds, *new_x_arginds)
737733

@@ -741,13 +737,13 @@ def interp_func(
741737
elem for pair in zip(rechunked, args[1::2], strict=True) for elem in pair
742738
)
743739

744-
new_x = rechunked[1 + (len(rechunked) - 1) // 2 :]
740+
new_x = rechunked[1 + (len(rechunked) - 1) // 2 :] # type: ignore[assignment]
745741

746742
new_x0_chunks = new_x[0].chunks
747743
new_x0_shape = new_x[0].shape
748744
new_x0_chunks_is_not_none = new_x0_chunks is not None
749745
new_axes = {
750-
ndim + i: new_x0_chunks[i] if new_x0_chunks_is_not_none else new_x0_shape[i]
746+
ndim + i: new_x0_chunks[i] if new_x0_chunks_is_not_none else new_x0_shape[i] # type: ignore[index]
751747
for i in range(new_x[0].ndim)
752748
}
753749

@@ -757,7 +753,7 @@ def interp_func(
757753
# scipy.interpolate.interp1d always forces to float.
758754
# Use the same check for blockwise as well:
759755
if not issubclass(var.dtype.type, np.inexact):
760-
dtype = float
756+
dtype = np.dtype(float)
761757
else:
762758
dtype = var.dtype
763759

@@ -772,18 +768,18 @@ def interp_func(
772768
localize=localize,
773769
concatenate=True,
774770
dtype=dtype,
775-
new_axes=new_axes,
771+
new_axes=new_axes, # type: ignore[arg-type]
776772
meta=meta,
777773
align_arrays=False,
778774
)
779775

780-
return _interpnd(var, x, new_x, func, kwargs)
776+
return _interpnd(var.data, x, new_x, func, kwargs)
781777

782778

783779
def _interp1d(
784780
var: np.ndarray,
785-
x: IndexVariable,
786-
new_x: IndexVariable,
781+
x: Variable,
782+
new_x: Variable,
787783
func: Callable,
788784
kwargs: dict,
789785
) -> np.ndarray:
@@ -798,8 +794,8 @@ def _interp1d(
798794

799795
def _interpnd(
800796
var: np.ndarray,
801-
x: list[IndexVariable],
802-
new_x: list[IndexVariable],
797+
x: tuple[Variable, ...],
798+
new_x: tuple[Variable, ...],
803799
func: Callable,
804800
kwargs: dict,
805801
) -> np.ndarray:

xarray/core/utils.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -132,7 +132,7 @@ def get_valid_numpy_dtype(array: np.ndarray | pd.Index) -> np.dtype:
132132
if not is_valid_numpy_dtype(array.dtype):
133133
return np.dtype("O")
134134

135-
return array.dtype # type: ignore[return-value]
135+
return array.dtype
136136

137137

138138
def maybe_coerce_to_str(index, original_coords):
@@ -180,7 +180,7 @@ def equivalent(first: T, second: T) -> bool:
180180
return duck_array_ops.array_equiv(first, second)
181181
if isinstance(first, list) or isinstance(second, list):
182182
return list_equiv(first, second) # type: ignore[arg-type]
183-
return (first == second) or (pd.isnull(first) and pd.isnull(second)) # type: ignore[call-overload]
183+
return (first == second) or (pd.isnull(first) and pd.isnull(second))
184184

185185

186186
def list_equiv(first: Sequence[T], second: Sequence[T]) -> bool:

xarray/core/variable.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -151,7 +151,7 @@ def as_variable(
151151
) from error
152152
elif utils.is_scalar(obj):
153153
obj = Variable([], obj)
154-
elif isinstance(obj, pd.Index | IndexVariable) and obj.name is not None:
154+
elif isinstance(obj, pd.Index | IndexVariable) and obj.name is not None: # type: ignore[redundant-expr]
155155
obj = Variable(obj.name, obj)
156156
elif isinstance(obj, set | dict):
157157
raise TypeError(f"variable {name!r} has invalid type {type(obj)!r}")

xarray/groupers.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -296,7 +296,7 @@ def factorize(self, group: T_Group) -> EncodedGroups:
296296

297297
data = np.asarray(group.data) # Cast _DummyGroup data to array
298298

299-
binned, self.bins = pd.cut( # type: ignore [call-overload]
299+
binned, self.bins = pd.cut(
300300
data.ravel(),
301301
bins=self.bins,
302302
right=self.right,

0 commit comments

Comments
 (0)